Using dependecy injection correctly

I am using Autofac to implement IoC in my solution, but I doubt if I am doing it right or not. Here's the scenario:
I have several classes Manager

that all come from a class BaseManager

. BaseManager

has a field protected User CurrentUser

. What I am trying to do is allow CurrentUser

with Autofac. I wrote an interface IUserProvider

and implemented a couple of classes (like WebUserProvider

and WinformsUserProvider

).
Then I registered my provider as shown below (for example in Global.asax)

:

builder.Register(c => new WebUserProvider(...)).As<IUserProvider>();  

      

  • How do I resolve dependencies (access container

    in my classes)? I could use the singleton or locator pattern, but it looks like an anti-pattern . So how do I resolve my addiction?
+3


source to share


1 answer


It seems to me that this is too difficult. Why do you have a base manager class that knows about the user? Having multiple manager classes is a code smell and a danger to maintain yourself as you abstract too much. Do you really need it?

How can I resolve dependencies (access container in my classes)?



You shouldn't be looking for a way to access your container. The container must be initialized once, in one place. You must inject all dependencies through the constructor. These dependencies are passed from the root of the dependency graph using container.Resolve<T>

and elsewhere in the dependency graph using constructor injection (or some people use property injection).

+5


source







All Articles