1

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?

4
  • What is DropCreateDatabaseIfModelChanges? Commented Oct 9, 2011 at 13:35
  • I'm using a code-first approach in development for my website. So when I change a Model, the MVC Framework drops the Database and creates it again; the structure of the table depending on how the models look. Commented Oct 9, 2011 at 13:40
  • DropCreateDatabaseIfModelChanges sounds scary :-) Commented Oct 9, 2011 at 14:33
  • Yeah it is xD But I only use it in development, and it accepts a seed so you can populate the database automatically. Commented Oct 9, 2011 at 15:17

1 Answer 1

1

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!!!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.