Dynamic dependency determination based on user parameters

Problem

I currently have a factory that depends on several parameters in order to correctly decide which object will be returned. This factory is not yet associated with DI. As far as I understand, NInject uses providers as a factory.

Here is what I have now. I will warn you that this is ugly.

public interface IRole
{
    string Name { get; }
}

public class FooRole : IRole
{
    public string Name { get { return "Foo Role"; } }
}

public class BarRole : IRole
{
    public string Name { get { return "Bar Role"; } }
}

public class FooBarRoleModule : NinjectModule
{
    public override void Load()
    {
        Bind<IRole>().ToProvider<RoleProvider>();
    }
}

public class RoleProvider : Provider<IRole>
{
    protected override IRole CreateInstance(IContext context)
    {
        var isNewParameter = context.Parameters
            .Where(x => x.Name == "isNew")
            .Select(x => x.GetValue(context))
            .Cast<bool>()
            .FirstOrDefault();

        if (isNewParameter) return new FooRole();
        return new BarRole();
    }
}

var role = kernel.Get<IRole>(new ConstructorArgument("isNew", true));
Console.WriteLine(role.Name);

I am pretty sure that this is not the right way to dynamically add dependencies, but it works. And honestly, looking at what I hacked together does not seem to make much sense.

, , , . , ( onlyNew) , .

, ? , , .

.

public class RoleFactory : IRoleFactory
{
    public IRole Create(bool isNew)
    {
        if (isNew) return new BarRole();
        return new FooRole();
    }
}

Bind<IRoleFactory>().To<RoleFactory>(); .

var role = kernel.Get<IRoleFactory>();
Console.WriteLine(role.Create(true).Name);

, , . , isNew , factory, , " ".

+5
1

Ninject . , . :

:

kernel.Bind<IRole>().To<FooRole>().Named("old");
kernel.Bind<IRole>().To<BarRole>().Named("new");
kernel.Get<IRole>("new");

kernel.Bind<IRole>().To<AdminRole>().When(ctx => UserHasAdminPermission())
kernel.Bind<IRole>().To<UserRole>();
kernel.Get<IRole>();
+6

All Articles