AutoMapper 4.2 和 Ninject 3.2
AutoMapper 4.2 and Ninject 3.2
我正在更新我的一个项目以使用 AutoMapper 4.2,并且我 运行 进行了重大更改。虽然我似乎 已经解决了上述更改,但我并不完全相信我已经以最合适的方式完成了。
在旧代码中,我有一个 NinjectConfiguration
和一个 AutoMapperConfiguration
class,它们分别由 WebActivator 加载。在新版本中 AutoMapperConfiguration
退出,我直接在 NinjectConfiguration
class 中实例化 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 绑定 AutoMapper 4.2 的合适方法吗?到目前为止它似乎在工作,但我只是想确定一下。
在库中不存在 IMapper 接口之前,您必须在下面实现接口和 class 并将它们绑定为单例模式。
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 接口绑定到 mapperConfiguration.CreateMapper()
的单个实例
您的代码存在问题,您应该使用单个实例(或如 Ninject 所说的常量)绑定。
// 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);
我正在更新我的一个项目以使用 AutoMapper 4.2,并且我 运行 进行了重大更改。虽然我似乎 已经解决了上述更改,但我并不完全相信我已经以最合适的方式完成了。
在旧代码中,我有一个 NinjectConfiguration
和一个 AutoMapperConfiguration
class,它们分别由 WebActivator 加载。在新版本中 AutoMapperConfiguration
退出,我直接在 NinjectConfiguration
class 中实例化 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 绑定 AutoMapper 4.2 的合适方法吗?到目前为止它似乎在工作,但我只是想确定一下。
在库中不存在 IMapper 接口之前,您必须在下面实现接口和 class 并将它们绑定为单例模式。
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 接口绑定到 mapperConfiguration.CreateMapper()
的单个实例您的代码存在问题,您应该使用单个实例(或如 Ninject 所说的常量)绑定。
// 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);