AutoMapper 4.2和Ninject 3.2 [英] AutoMapper 4.2 and Ninject 3.2
问题描述
我正在更新我的项目以使用AutoMapper 4.2,并且遇到了重大更改.尽管我似乎已经解决了上述更改,但我并不完全相信我已经以最适当的方式做到了.
I'm updating a project of mine to use AutoMapper 4.2, and I'm running into breaking changes. While I seem to have resolved said changes, I'm not entirely convinced I've done so in the most appropriate way.
在旧代码中,我有一个NinjectConfiguration
和一个AutoMapperConfiguration
类,它们分别由WebActivator加载.在新版本中,AutoMapperConfiguration
退出,而我直接在发生绑定的NinjectConfiguration
类中直接实例化MapperConfiguration
,例如:
In the old code, I have a NinjectConfiguration
, and an AutoMapperConfiguration
class that are each loaded by WebActivator. In the new version the AutoMapperConfiguration
drops out and I instead instance a MapperConfiguration
directly in the NinjectConfiguration
class where the bindings are happening, like so:
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的适当方法吗?到目前为止,它似乎仍在工作,但我只是想确定一下.
So, is this the appropriate way of binding AutoMapper 4.2 using Ninject? It seems to be working so far, but I just want to make sure.
推荐答案
在库中不存在IMapper接口之前,您必须在下面实现接口和类并将它们绑定为单例模式.
In before IMapper interface didn't existed in the library so you had to implement interface and class below and bound them as a singleton pattern.
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()的单个实例
Now you simply bind library's IMapper interface to single instance of mapperConfiguration.CreateMapper()
代码问题,您应该使用单个实例(或如Ninject所说的常量)绑定.
The Problem with your code tho, you should use a single instance(or as Ninject says, a constant) 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);
这篇关于AutoMapper 4.2和Ninject 3.2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!