Ole*_*Aza 2 c# reflection ninject automapper
我正在尝试使用Ninject自动注册AutoMapper配置文件.为此,我需要实例化从AutoMapper.Profile继承的类型的对象,例如:
public class WordMapping : Profile
{
protected override void Configure()
{
Mapper.CreateMap<Datacontext.Entities.Word, Domain.Entities.Word>();
Mapper.CreateMap<Domain.Entities.Word, Datacontext.Entities.Word>();
}
}
Run Code Online (Sandbox Code Playgroud)
首先,我试图通过反射来做到这一点,它就像一个魅力:
var profileType = typeof(AutoMapper.Profile);
var profiles = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(a => a.GetTypes())
.Where(t => profileType.IsAssignableFrom(t) && t.GetConstructor(Type.EmptyTypes) != null)
.Select(Activator.CreateInstance)
.Cast<Profile>();
foreach (var profile in profiles)
{
Mapper.AddProfile(profile);
}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试用Ninject做同样的事情时:
public class MappingModules : NinjectModule
{
public override void Load()
{
Kernel.Bind(scanner =>
{
scanner.FromAssembliesMatching("*")
.SelectAllClasses()
.InheritedFrom<AutoMapper.Profile>();
});
var profiles = Kernel.GetAll<Profile>();
foreach (var profile in profiles)
{
Mapper.AddProfile(profile);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我收到错误:
SetUp:Ninject.ActivationException:使用Profile No构造函数的隐式自绑定激活Profile时出错可用于创建实现类型的实例.
激活路径:1)请求配置文件
建议:1)确保实现类型具有公共构造函数.2)如果已实现Singleton模式,请使用与InSingletonScope()的绑定.
我怀疑这是因为Ninject尝试实例化Mapper.Profile本身,但它没有公共构造函数.但是,当我改变.InheritedFrom<AutoMapper.Profile>()到.Where(p => p.IsAssignableFrom(typeof(AutoMapper.Profile)) && p != typeof(AutoMapper.Profile))它并没有帮助.
值得一提的是,Ninject的组合根,Ninject的模块和继承自的类AutoMapper.Profile位于3个不同的程序集中.
请帮我弄清楚我错过了什么.
基于约定的约束缺失....绑定!添加.BindBase()到条件绑定的末尾.
Kernel.Bind(scanner =>
{
scanner.FromAssembliesMatching("*")
.SelectAllClasses()
.InheritedFrom<AutoMapper.Profile>()
.BindBase();
});
Run Code Online (Sandbox Code Playgroud)
BindBase()将类绑定到它的直接基类,在您的示例(WordMapping : Profile)中Profile.如果你的继承层次结构将会WordMapping : MyMapping : Profile绑定MyMapping(这对你来说不合适).因此,如果您需要将其绑定到其他类型,请查看https://github.com/ninject/ninject.extensions.conventions/wiki/Projecting-Services-to-Bind