I am using Autofac for IoC in my project. Due to some legacy software libraries I must pass some services to the controller that can't be resolved, and must be passed as parameter.
I've made a generic control using delegate factories like this:
public MyClass<TController, TInterface> {
private delegate TController ControllerFactory(TInterface service);
protected TController _myController;
protected TController Controller {
get
{
return _controller
?? (_controller = ServiceLocator.Resolve<ControllerFactory>()
.Invoke(this);
}
}
}
This works perfect, but for this to work I need the controller's service parameter name and the delegate service parameter name be the same, because as I have read, Autofac pairs the parameter BY NAME !!
I've seen you can do it by type registering the class with generic Func<>, but due to the legacy app I would need to leave "clean" registrations i.e.:
containerBuilder.RegisterType<MyController>();
Does anyone know if it's possible to make the delegate match the parameter by type??
Yes, you can use predefined delegates. See dynamic instantiation section here.
Here's an quick example:
Registration + Usage
**Be warned, if you use this method, Autofac throws an exception if you try to add parameters with of the same type. Ex.
Component
has two dependencies onDependency
Exception looks something like this:
Autofac is more specific about what type you register the controller as than most DI containers. It will only resolve the type by its type if you include
.AsSelf()
in the registration of the controller. Here is a module we use in our project for registering MVC controllers.Using this registration, you can resolve each controller by controller type.