I’m using Autofac to implement IoC in my solution, But I am doubtful whether I’m doing it right or not. Here’s the scenario:
I have some Manager classes which all derive from BaseManager class. The BaseManager has a protected User CurrentUser field. What I’m trying to do, is to resolve the CurrentUser using Autofac. I have written anIUserProvider interface and implemented a couple of classes (e.g. WebUserProvider and WinformsUserProvider).
Then I registered my provider as below (for example, in Global.asax):
builder.Register(c => new WebUserProvider(...)).As<IUserProvider>();
- How can I resolve dependencies (access
containerin my classes)? I could use a singleton or a service locator pattern but seems like it’s an anti-pattern. So how should I resolve my dependency?
This sounds like overengineering to me. Why would you have a base manager class that has knowledge of the user? Having a few manager classes is a code smell and a maintenance hazard on its own, as your are abstracting too much. Do you really need that?
You should not be looking for a way to access your container. Container must be initialized once, in a single place. You should inject all the dependencies via constructor. These dependencies are passed in from the root of the dependency graph using
container.Resolve<T>and elsewhere in the dependency graph using constructor injection (or some folks use property injection).