我正在更新我的一个项目以使用 AutoMapper 4.2,并且我遇到了重大更改。虽然我似乎已经解决了上述更改,但我并不完全相信我已经以最合适的方式完成了。
在旧代码中,我有一个 NinjectConfiguration
和一个 AutoMapperConfiguration
类,它们均由 WebActivator 加载。在新版本中,AutoMapperConfiguration
消失了,我改为直接在发生绑定(bind)的 NinjectConfiguration
类中实例化一个 MapperConfiguration
,如下所示:
private static void RegisterServices(
IKernel kernel) {
var profiles = AssemblyHelper.GetTypesInheriting<Profile>(Assembly.Load("???.Mappings")).Select(Activator.CreateInstance).Cast<Profile>();
var config = new MapperConfiguration(
c => {
foreach (var profile in profiles) {
c.AddProfile(profile);
}
});
kernel.Bind<MapperConfiguration>().ToMethod(
c =>
config).InSingletonScope();
kernel.Bind<IMapper>().ToMethod(
c =>
config.CreateMapper()).InRequestScope();
RegisterModules(kernel);
}
那么,这是使用 Ninject 绑定(bind) AutoMapper 4.2 的合适方法吗?到目前为止它似乎有效,但我只是想确认一下。
最佳答案
在库中不存在 IMapper 接口(interface)之前,您必须在下面实现接口(interface)和类并将它们绑定(bind)为单例模式。
public interface IMapper
{
T Map<T>(object objectToMap);
}
public class AutoMapperAdapter : IMapper
{
public T Map<T>(object objectToMap)
{
//Mapper.Map is a static method of the library!
return Mapper.Map<T>(objectToMap);
}
}
现在您只需将库的 IMapper 接口(interface)绑定(bind)到 mapperConfiguration.CreateMapper() 的单个实例
您的代码存在问题,您应该使用单个实例(或如 Ninject 所说,常量)绑定(bind)。
// A reminder
var config = new MapperConfiguration(
c => {
foreach (var profile in profiles) {
c.AddProfile(profile);
}
});
// Solution starts here
var mapper = config.CreateMapper();
kernel.Bind<IMapper>().ToConstant(mapper);
关于c# - AutoMapper 4.2 和 Ninject 3.2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35233989/