N
N
no0ob2016-05-12 01:53:40
ASP.NET
no0ob, 2016-05-12 01:53:40

[DI] Resolve type inside controller method (ASP.MVC). How to implement?

Good day.
My project has a bunch of different repositories and their interfaces. In the controller method, I would like to receive the implementation of a specific repository as follows:

public ActionResult SomeMethod(){
   var someRepo = ObjectFactory.Resolve<ISomeRepository>();
   return Content(someRepo.SomeAction());
}

There is a lot of information on the internet about various DI containers (Ninject, Unity...). The problem is that they resolve constructor parameters. I was thinking of using Unity the way I wrote above, but I came across this link unity.codeplex.com/discussions/640841 which says that it's not good to use Unity this way.
Are there any out-of-the-box solutions to resolve types inside a controller method (preferably customizable via XML like in Unity)?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
Fat Lorrie, 2016-05-12
@Free_ze

DependencyResolver.Current.GetService(typeof(IMyService))

V
Valery Abakumov, 2016-06-17
@Valeriy1991

Are there any out-of-the-box solutions to resolve types inside a controller method (preferably customizable via XML like in Unity)?

Good afternoon!
If you are trying to resolve something from an IoC container in an action method, then you are on the wrong path (because resolving directly from the container leads to significant memory leaks due to the fact that the GC cannot clean them up, since they are "used" by the IoC container itself). What's stopping you from passing your ISomeRepository to the controller's constructor and writing it to a private field?
I would do as Free_ze suggested in the comments to your question:
The controller will look like this in this case:
private readonly ISomeRepository _someRepo;
public MyController(ISomeRepository someRepo)
{
    if(someRepo == null)
        throw new ArgumentNullException(nameof(someRepo));
    _someRepo = someRepo;
}

Then we use _someRepo to our heart's content. This approach is more correct in terms of dependency resolution. About the IoC container, in fact, only the one who configures it should know.
PS Bonus: if you have a lot of repositories and interfaces for them, then it's time for refactoring. Look towards GenericRepository + UnitOfWork.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question