MVC Controller Generic injection with AutoFac

I am new to DI with Autofac and am wondering if the following is possible:

I want to create a general controller and an action that receives an injected type. I do not need an instance of the input type, but I just need its type, which will implement the expected interface.

I would also like to pass this generic type into a ViewModel, but this is a completely different subject, however, if any genius there can decide, then that would be great.

public ContractorController<T> : Controller 
    where T : IContractor{ 

    public ViewResult New() { 
            var vNewModel = new NewViewModel<T>(); 
            return View(vNewModel); 
        } 
} 

This controller must be called http://mysite.com/Contractor/New

I'm doing generics registration with AutoFac, but it seems like the problem is that AutofacControllerFactory only implements GetControllerInstance (), expecting the type of controller to be passed to it from GetController () or CreateController (), but not sure what or what is between there is a difference between them. These methods get the controller name as a string from RoutData and return the corresponding .NET type, which gives the URL, http://mysite.com/Contractor/Newis the controller = Contractor, and thus the ContractorController cannot be mapped to GetController () or CreateController () and passed before it null is GetControllerInstance (), which means that AutofacControllerFactory is not trying to resolve the type.

, Factory AutofacControllerFactory, GetController() CreateController() . -

if (controllerName == "" )   return System.Type.GetType(        "UI.Controllers". + controllerName + "Controller`1" );

, , .

, ,

builder.RegisterType<FakeContractor>().As<IContractor>(); 
builder.RegisterGeneric(typeof(ContractorController<>)); 

:

The Autofac service 
'UI.Controllers.ContractorController`1' 
representing controller 
'ContractorManagement.UI.Controllers.ContractorController`1' 
in path '/Contractor/New' has not been registered. 

, . - , ,

+3
2

, , . Mvc - , , . , ?

, , . , .

, Mvc2 IocModelBinder. Autofac. autofac.

- , DerivedTypeModelBinder MvcContrib. , Mvc 1, 2, MvcContrib Mvc3 . Mvc3 - , .

0

, , , - :

public abstract class ContractorControllerBase<T> : Controller where T : IContractor { 
    public ViewResult New() { 
        var vNewModel = new NewViewModel<T>(); 
        return View(vNewModel); 
    } 
} 

public class FakeContractorController : ContractorControllerBase<FakeContractor> {
}
0

Source: https://habr.com/ru/post/1786104/


All Articles