Hopefully I can explain this to where someone might understand it enough to help 🙂
Anyways, I want to take a property from an injected type and use that in another injection. So imagine you have MVC model state on a controller that you want to inject into a service the controller uses.
public class MyController
{
public MyController(IService service)
{
....
}
}
public class MyService : IService
{
public MyService(IModelStateWrapper modelState)
{
....
}
}
How can I accomplish basically this:
public class MyController
{
public MyController(IService service)
{
service.ModelState = new ModelStateWrapper(ModelState);
}
}
Using an injection with Autofac or whatever DI container.
You can do this, but you have to unravel a couple of design problems before it’s possible.
First, it appears that your
IServiceimplementation requires you pass theIModelStateWrapperin during construction only to be overwritten later during the creation of the controller. You have to make it so theIServiceimplementation only has it as a property, not as a constructor requirement.Second, you have to make sure it’s OK that the
service.ModelStatesetting happens just after construction of the controller. If there is other constructor logic that assumes theservice.ModelStateis set, then you have something that can’t really be done via DI.If you do that unraveling, Autofac will let you do some pretty cool stuff. When you register your controller type, register a lambda instead of just a type.
Note the circular logic thing is handled in the lambda of the registration. Now when you resolve a controller…
…that logic will run and you’ll get the effect you’re looking for.
Again, I’ll voice some concern over the circular reference stuff going on here. If there’s a way to remove that circular dependency between the controller and the service, you’d be in a better spot to let DI work for you.