C# 如何使用Ninject在当前AppDomain程序集中实例化特定类型的对象?
我正在尝试用Ninject自动注册AutoMapper配置文件。为此,我需要实例化从AutoMapper.Profile继承的类型的对象,例如:C# 如何使用Ninject在当前AppDomain程序集中实例化特定类型的对象?,c#,reflection,ninject,automapper,C#,Reflection,Ninject,Automapper,我正在尝试用Ninject自动注册AutoMapper配置文件。为此,我需要实例化从AutoMapper.Profile继承的类型的对象,例如: public class WordMapping : Profile { protected override void Configure() { Mapper.CreateMap<Datacontext.Entities.Word, Domain.Entities.Word>(); Map
public class WordMapping : Profile
{
protected override void Configure()
{
Mapper.CreateMap<Datacontext.Entities.Word, Domain.Entities.Word>();
Mapper.CreateMap<Domain.Entities.Word, Datacontext.Entities.Word>();
}
}
公共类WordMapping:Profile
{
受保护的覆盖无效配置()
{
CreateMap();
CreateMap();
}
}
首先,我试图通过反思来实现这一点,但效果很好:
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);
}
var profileType=typeof(AutoMapper.Profile);
var profiles=AppDomain.CurrentDomain.GetAssemblys()
.SelectMany(a=>a.GetTypes())
.Where(t=>profileType.IsAssignableFrom(t)&&t.GetConstructor(Type.EmptyTypes)!=null)
.Select(Activator.CreateInstance)
.Cast();
foreach(配置文件中的var配置文件)
{
Mapper.AddProfile(profile);
}
但当我试着用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);
}
}
}
公共类映射模块:NinjectModule
{
公共覆盖无效负载()
{
Bind(scanner=>
{
scanner.FromAssembliesMatching(“*”)
.SelectAllClasses()
.继承自();
});
var profiles=Kernel.GetAll();
foreach(配置文件中的var配置文件)
{
Mapper.AddProfile(profile);
}
}
}
我得到一个错误:
设置:Ninject.ActivationException:使用激活配置文件时出错
配置文件的隐式自绑定没有可用的构造函数
创建实现类型的实例
激活路径:1)请求配置文件
建议:1)确保实现类型具有公共
构造器。2) 如果已经实现了Singleton模式,请使用
改为使用InSingletonScope()绑定
我怀疑这是因为Ninject试图实例化Mapper.Profile本身,但它没有公共构造函数。但是,当我将.InheritedFrom()
更改为.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();
});
Kernel.Bind(scanner=>
{
scanner.FromAssembliesMatching(“*”)
.SelectAllClasses()
.InheritedFrom这似乎可行,但我不明白…配置文件如何具有受保护的构造函数。存在一个公共初始化()但是我不知道ninject怎么知道调用这个方法。现在我担心我的配置文件没有正确加载。好的,我检查了源文件和配置文件。Initialize是从Mapper.Initialize中调用的。但是它仍然需要一个新的配置文件实例。它如何使用受保护的ctor?我也看到了一个内部ctor,但它需要一个str你说得对,ninject不能调用new Profile()
,它也不必调用。它实际上是在调用new WordMapping()
。由于WordMapping:Profile
,它可以在实例化后安全地“铸造”到Profile
。