开发者

Should (and if so how should) a database context be dependency injected into a controller?

开发者 https://www.devze.com 2023-02-28 08:53 出处:网络
It seems like at least 90+% of the Controller Actions I am writing will need to access the database. To me it seems like a logical step to have the database context automatically injected.

It seems like at least 90+% of the Controller Actions I am writing will need to access the database. To me it seems like a logical step to have the database context automatically injected.

I have ne开发者_Python百科ver used dependency injection before so I want to confirm this is something that is a pattern. If it is, how should I go about doing this? I know ASP.NET MVC 3 has "improved dependency injection" support, but do I still need an external framework? If so what is the default and how do I configure it to create a new database context per http request?


ASP.NET MVC 3 doesn't have improved DI support - it has improved support for the Service Locator anti-pattern (go figure). Fortunately it has had support for DI since MVC 1 through the IControllerFactory interface.

To answer the question, however, yes, it sounds like a perfectly normal thing to inject a Repository into a Controller (although normally we would slide a Domain Model in between the two).

This is best done with Constructor Injection like this:

public class MyController
{
    private readonly IMyRepository repository;

    public MyController(IMyRepository repository)
    {
        if (repository == null)
        {
            throw new ArgumentNullException("repository");
        }

        this.repository = repository;
    }

    public ViewResult MyAction(int barId)
    {
        var bar = this.repository.SelectBar(barId);
        return this.View(bar);
    }
}

You'll need to provide a custom IControllerFactory to enable Constructor Injection with the MVC framework - the easiest thing is to derive from DefaultControllerFactory.

Once you have a custom IControllerFactory, you can register it in Global.asax like this:

ControllerBuilder.Current.SetControllerFactory(new MyControllerFactory());
0

精彩评论

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