簡體   English   中英

當我嘗試將Autofac與AutoMapper的IMappingEngine結合使用時發生異常

[英]Exception when I try to combine Autofac with AutoMapper`s IMappingEngine

那就是我的DI和Automapper設置:

[RoutePrefix("api/productdetails")]
public class ProductController : ApiController
{
    private readonly IProductRepository _repository;
    private readonly IMappingEngine _mappingEngine;

    public ProductController(IProductRepository repository, IMappingEngine mappingEngine)
    {
        _repository = repository;
        _mappingEngine = mappingEngine;
    }
}

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);

        //WebApiConfig.Register(GlobalConfiguration.Configuration);          
        RouteConfig.RegisterRoutes(RouteTable.Routes);          
    }
}


public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();
        config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional });

        // Filter
        config.Filters.Add(new ActionExceptionFilter());
        config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler());


        // DI
        // Register services
        var builder = new ContainerBuilder();
        builder.RegisterType<ProductRepository>().As<IProductRepository>().InstancePerRequest();
        builder.RegisterType<MappingEngine>().As<IMappingEngine>();

        // AutoMapper
        RegisterAutoMapper(builder);

        // FluentValidation

        // do that finally!
        // This is need that AutoFac works with controller type injection
        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
        var container = builder.Build();
        config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
    }

    private static void RegisterAutoMapper(ContainerBuilder builder)
    {
        var profiles =
            AppDomain.CurrentDomain.GetAssemblies()
                .SelectMany(GetLoadableTypes)
                .Where(t => t != typeof (Profile) && typeof (Profile).IsAssignableFrom(t));
        foreach (var profile in profiles)
        {
            Mapper.Configuration.AddProfile((Profile) Activator.CreateInstance(profile));
        }

    }

    private static IEnumerable<Type> GetLoadableTypes(Assembly assembly)
    {
        try
        {
            return assembly.GetTypes();
        }
        catch (ReflectionTypeLoadException e)
        {
            return e.Types.Where(t => t != null);
        }
    }
}

那是我去某條路線時遇到的異常:

None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'AutoMapper.MappingEngine' can be invoked with the available services and parameters:
Cannot resolve parameter 'AutoMapper.IConfigurationProvider configurationProvider' of constructor 'Void .ctor(AutoMapper.IConfigurationProvider)'.
Cannot resolve parameter 'AutoMapper.IConfigurationProvider configurationProvider' of constructor 'Void .ctor(AutoMapper.IConfigurationProvider, AutoMapper.Internal.IDictionary`2[AutoMapper.Impl.TypePair,AutoMapper.IObjectMapper], System.Func`2[System.Type,System.Object])'.

我的代碼有什么問題?

錯誤來自此行:

builder.RegisterType<MappingEngine>().As<IMappingEngine>();

此行告訴Autofac在需要MappingEngine時實例化IMappingEngine 如果查看MappingEngine的可用構造函數,您會發現Autofac無法使用其中的任何一個,因為它無法注入必需的參數。

這是MappingEngine可用的構造MappingEngine

public MappingEngine(IConfigurationProvider configurationProvider)
public MappingEngine(IConfigurationProvider configurationProvider, 
                     IDictionary<TypePair, IObjectMapper> objectMapperCache, 
                     Func<Type, object> serviceCtor)

解決此問題的一種方法是告訴Autofac如何創建您的MappingEngine您可以使用委托注冊來完成。

builder.Register(c => new MappingEngine(...)).As<IMappingEngine>();

您還可以通過這樣做注冊IConfigurationProviderAutofac將能夠自動找到合適的構造函數。

解決此問題的最簡單方法是在Autofac中注冊IConfigurationProvider

builder.Register(c => new ConfigurationStore(new TypeMapFactory(), MapperRegistry.Mappers))
       .As<IConfigurationProvider>()
       .SingleInstance();
builder.RegisterType<MappingEngine>()
       .As<IMappingEngine>();

您還可以在這里找到更多信息: AutoMapper,Autofac,Web API和每個請求依賴項生存期范圍

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM