简体   繁体   中英

Asp.net MVC Dependency Injection in generics

Currently I'm using DI and IoC to control some parts of my website. I don't know alot about it, but I've been trying to understand it by using. I'm using StructureMap

My controllers have the following Contructor

    IDbContext _db;

    public PagesController(IDbContext db)
    {
        _db = db;
    }

Obviously this doesn't work immediatly, so I've created the following dependency

x.For<IDbContext>().Use<ContextDb>();

Confusing enough, I've called the application "Context" -> hence ContextDb (don't confuse it with DbContext or IDbContext )

Allright, now my problem. In the Global.asax file I decided I wanted to DropCreateDatabaseIfModelChanges , so I went and added the following:

DbDatabase.SetInitializer<IDbContext>(new DropCreateDatabaseIfModelChanges<IDbContext>));

Obviously this isn't working, IDbContext is an interface, and the dependency rules decide what implementation is used. So the only way to make this work is to use the following:

DbDatabase.SetInitializer<ContextDb>(new DropCreateDatabaseIfModelChanges<ContextDb>));

However, that kinda defeats the purpose of this dependency injection right? How could I solve this?

You could set the ContextDB class into Web.Config and use ConfigurationManager to get it or some Configuration File and set the Activator to call it on Global.asax.cs like the code below:

String configString = ConfigurationManager.AppSettings["MyDBContextType"];
IDBContext db = (IDBContext)Activator.CreateInstance(Type.GetType(configString));

That would keep the purpose of this dependency injection.

Hope it helps!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM