开发者

Using Ninject dynamically to connection to different databases

I have an MVC application using Ninject to connect to a single database. Now I need to support multiple databases. Currently, my global.asax.cs file has the following definition for ninject:

    protected void Application_Start() 
    { 
        AreaRegistration.RegisterAllAreas(); 
        RegisterRoutes(RouteTable.Routes); 

        //Using DI for controllers - use the Ninject custom controller factor 
        ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory()); // Repository config is defined in ninject controller 
    }

And here is what my Ninject controller class looks like:

public class NinjectControllerFactory : DefaultControllerFactory 
{ 
    private IKernel kernel = new StandardKernel(new EriskServices()); 

    protected override IController GetControllerInstance(RequestContext context, Type controllerType) 
    { 
        if (controllerType == null) 
            return null; 
        return (IController)kernel.Get(controllerType); 
    } 

    private class EriskServices : NinjectModule 
    { 
        public override void Load() 
        { 
            Bind<IRisksRepository>().To<MySql_RisksRepository>() 
                .WithConstructorArgument("connectionString", ConfigurationManager.ConnectionStrings["mydb1"].ConnectionString); 
        } 
    } 
}

I also have a login page that handles user authentication. It is done through LDAP and does not require database connection.

My question is: Can I bind the ninject connectionString after the user authentication login page? The user would have a dropdown list for d开发者_StackOverflow中文版atabase they want to connect to, for example "mydb1" or "mydb2" or "mydb3". Each connection string would be defined in the web.config file.

Please help! Thank you!


No, you can't bind "after" - for one thing, web applications are stateless and you have no control over the order of events, but more importantly, Ninject modules define your IoC container and this configuration happens before almost anything else in the application or request lifecycle.

If you're saying that the user would pick this from a drop-down, then the act of choosing the repository is part of your application logic, not part of your IoC configuration. The way to deal with this is to create a factory interface. The implementation can be a thin wrapper around the Ninject kernel itself.

public interface IRisksRepositoryFactory()
{
    IRisksRepository GetRepository(string name);
    // Optional: add a GetRepositoryNames() method for populating dropdowns, etc.
}

public class NinjectRisksRepositoryFactory
{
    private readonly IKernel kernel;

    public NinjectRisksRepositoryFactory(IKernel kernel)
    {
        if (kernel == null)
            throw new ArgumentNullException("kernel");
        this.kernel = kernel;
    }

    public IRisksRepository GetRepository(string name)
    {
        return kernel.Get<IRisksRepository>(name);
    }
}

For this particular implementation you'd want to make sure you use named bindings (although generally speaking you could also use the metadata system), and do each binding explicitly:

Bind<IRisksRepository>()
    .To<MySqlRisksRepository>()
    .InRequestScope()
    .Named("mysql")
    .WithConstructorArgument("connectionString", GetConnectionString("mydb1"));
Bind<IRisksRepository>()
    .To<OracleRisksRepository>()
    .InRequestScope()
    .Named("oracle")
    .WithConstructorArgument("connectionString", GetConnectionString("ordb1"));
Bind<IRisksRepositoryFactory>()
    .To<NinjectRisksRepositoryFactory>();

It's also possible to do this without creating each binding explicitly, particularly if all targets are the same type (i.e. you only have a MySqlRisksRepository), by passing the connection string or related symbol as a parameter to the Get call and binding to a contextual method instead of a type - but I'd recommend against it, since it's really swimming against the current as far as DI in general goes.

One more thing: Don't worry that this resembles the "service locator" anti-pattern, because that's all it is - a superficial resemblance. When objects need to be able to create dependencies on the fly, creating special-purpose factories around the IoC container is the recommended solution, as it minimizes kernel exposure to a single class which could be easily replaced if you switched to a different framework.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜