错误:没有AutoMapperConfiguration的无参数构造函数
我正在使用nuget包automapper DI
if let url = URL(string: "wss://ios-devchallenge-11.tk/write?id=id") {
socket = WebSocket(url: url, protocols: ["chat", "superchat"])
socket?.delegate = self
socket?.connect()
}
如何使用带参数的automapper DI?
答案 0 :(得分:2)
我认为您无法将DI参数添加到Profile
。这背后的部分逻辑可能是这些只是实例化一次,因此通过AddTransient
注册的服务将不会按预期运行。
一种选择是将其注入ITypeConverter
:
public class AutoMapperConfiguration : Profile
{
public AutoMapperConfiguration()
{
CreateMap<SourceModel, DestinationModel>().ConvertUsing<ExampleConverter>();
}
}
public class ExampleConverter : ITypeConverter<SourceModel, DestinationModel>
{
private readonly ICloudStorage _storage;
public ExampleCoverter(ICloudStorage storage)
{
// injected here
_storage = storage;
}
public DestinationModel Convert(SourceModel source, DestinationModel destination, ResolutionContext context)
{
// do conversion stuff
return new DestinationModel();
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<ICloudStorage, AzureStorage>();
services.AddAutoMapper();
}
答案 1 :(得分:1)
如果AddAutoMapper
是您构建的扩展程序,则可能需要在 Startup.cs 上尝试此操作,然后将以下代码添加到您的扩展程序中。
public void ConfigureServices(IServiceCollection services)
{
var mapperConfiguration = new MapperConfiguration(mc =>
{
IServiceProvider provider = services.BuildServiceProvider();
mc.AddProfile(new AutoMapperConfiguration (provider.GetService<ICloudStorage>()));
});
services.AddSingleton(mapperConfiguration.CreateMapper());
}
答案 2 :(得分:-1)
我找到了一种解决方案。
在添加配置文件之前创建一个类型列表,并将其传递给参数。
@Option(... defaultValue="...")