开发者

Right way to derive controllers from a base controller

I tend to consume the same set of repositories from all my controllers. That is, I instantiate repository 开发者_如何转开发objects (with IoC) in every controller.

I think I could derive my controllers from a base controller that could instantiate these objects in one place. Could you point me to the right of doing this? Thank you for your help.


You have a number of options, and which one is "the right way" is really up to you and how your system functions overall. There could be performance issues for various instantiated objects that need to be considered, etc.

One option could be as simple as:

public class BaseController
{
    protected ISomeRepository myRepository = IoCContainer.Resolve<ISomeRepository>();
}
public class MyController : BaseController { }

Additionally, you could move the initialization to the base controller's constructor rather than have it be inline like that.

Another option might be to late-bind the repositories, if having them all incurs a performance hit (weighed carefully with the hit of instantiating them) and on average they aren't always needed:

public class BaseController
{
    private ISomeRepository _myRepository;
    protected ISomeRepository myRepository
    {
        get
        {
            if (_myRepository == null)
                _myRepository = IoCContainer.Resolve<ISomeRepository>();
            return _myRepository;
        }
    }
}

There are probably more options available to you, it all depends on your setup. How your particular IoC container works may also play heavily into your design decision.

(Note that I reference the IoCContainer directly here for brevity and simplicity, but I recommend abstracting out the container behind a service locator so that you don't have so many references to the container itself.)


Actually, it depends on what kind of tasks should those "Common Repositories" complete. If they are directly relate to what Action supposed to do - maybe that is okay. But you'll anyway face some problems with IoC-resolution. In order to avoid injecting those repositories all the time for each new Repo you'll have to make a dependency on Service Locator in your base controller. Which isn't good thing.

If those Repositories are ther efor something that is orthogonal to what Action is going to do - then it is more like AOP-kinda logic, so I'd better use Action Filters for that or RenderAction.

In common case, I'd try to avoid layer supertype dependencies as well as would prefer Composition over Inheritance.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜