gpt4 book ai didi

c# - 此解析操作已结束。 Autofac、Automapper 和 IMemberValueResolver

转载 作者:太空宇宙 更新时间:2023-11-03 22:39:32 24 4
gpt4 key购买 nike

我对 Autofac 和 Automapper 有疑问。

在我的 WebApi 中,我有这段代码来注册我的类(class):

    public static void Initialize(HttpConfiguration config, IContainer container)
{
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
_container = container;
}

private static IContainer RegisterServices(ContainerBuilder builder)
{
//Register your Web API controllers.
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

builder.RegisterModule<MapperInstaller>();
builder.RegisterType<VurpEntities>();
builder.RegisterType<EntityFrameworkUnitOfWork>().As<IUnitOfWork>();

builder.RegisterType<AppService>().As<IAppService>();
builder.RegisterType<AppRepository>().As<IAppRepository>();

builder.RegisterType<BusinessService>().As<IBusinessService>();
builder.RegisterType<BusinessRepository>().As<IBusinessRepository>();

//...
//all my types are registered here
//...



//Set the dependency resolver to be Autofac.
_container = builder.Build();

return _container;
}

我创建了一个 Resolver 来映射我的对象的一个​​特殊字段:

public class ProductTypeResolver : IMemberValueResolver<ProductDto, Product, string, Enumeration.ProductType>
{
public ProductType Resolve(ProductDto source, Product destination, string sourceMember, ProductType destMember, ResolutionContext context)
{
Enum.TryParse(sourceMember, out destMember);

return destMember;
}
}

我有一个在实体对象中映射 DTO 对象的配置文件:

CreateMap<ProductDto, Product>()
.ForMember(dest => dest.Category, opt => opt.Ignore())
.ForMember(dest => dest.Feature, opt => opt.Ignore())
opts.ResolveUsing<ProductTypeResolver, string>(src => src.type));

当我尝试映射对象时 Product p = _mapper.Map<Product>(productDto);我收到错误:

An exception of type 'System.ObjectDisposedException' occurred in Autofac.dll but was not handled in user code

Additional information: This resolve operation has already ended. When registering components using lambdas, the IComponentContext 'c' parameter to the lambda cannot be stored. Instead, either resolve IComponentContext again from 'c', or resolve a Func<> based factory to create subsequent components from.

谁能帮帮我?

最佳答案

我用这个解决了:

    builder.Register(c =>
{
//This resolves a new context that can be used later.
var context = c.Resolve<IComponentContext>();
var config = context.Resolve<MapperConfiguration>();
return config.CreateMapper(context.Resolve);
})
.As<IMapper>()
.InstancePerLifetimeScope();

关于c# - 此解析操作已结束。 Autofac、Automapper 和 IMemberValueResolver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53047850/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com