Not*_*ple 9 c# ninject constructor-injection
我希望能够使用ninject将特定泛型类型的所有实例注入到类中.例如,我有一堆类似于以下格式的自定义提取器:
public interface IExtract<TEntity>
{
TEntity ExtractFrom(MyBulkExportedEntity exportedEntity);
}
Run Code Online (Sandbox Code Playgroud)
我想将这些提取器的所有实例注入一个负责使用ninject多重绑定处理该文件的类.
即
public class ProcessDataExtract
{
/*This isn't valid c# but demonstrates the intent of what i would like to do*/
public ProcessDataExtract(IEnumerable<IExtract<>> allExtractors)
{
}
public void Process(MyBulkExportedEntity exportedEntity)
{
/*loop through all of the extractors and pull relevant data from the object*/
}
}
Run Code Online (Sandbox Code Playgroud)
在过去,我通过一个管理类(IProvideExtractors)直接访问内核但我不喜欢这种方法并且想知道是否有人知道更好的方法来做到这一点.使用ninject多重绑定,我可以获得所有感兴趣的实例kernel.GetAll(typeof(IExtract<>))
我正在寻找相关的东西:我不想使用约定扩展单独指定所有绑定。
第一:你需要注入List<IExtract>并继承IExtract<T> : IExtract。这仅仅是因为,在 C# 中,您无法指定包含不同泛型的集合的类型。正如您在问题中指出的那样,这是无效的语法 - 除了这个答案之外,还有一个很好的理由。
您稍后可以将 的元素IExtract从列表中取出,并使用反射来获取泛型类型参数并将其转换回来。或者,如果您知道您正在寻找什么提取器:
public IExtract<T> GetExtractor<T>() {
return (IExtract<T>)Extractors.Find(e => e is ExtractImpl<T>);
}
Run Code Online (Sandbox Code Playgroud)
现在您可能有一堆类,您希望将其T绑定到 IExtract`。
Bind<IExtract>().To<ExtractImpl<MyEntity>>();
Bind<IExtract>().To<ExtractImpl<YourEntity>>();
Run Code Online (Sandbox Code Playgroud)
在哪里
MyEntity : BaseEntity
YourEntity : BaseEntity
Run Code Online (Sandbox Code Playgroud)
您可以指定一个约定,如下所示
Kernel.Bind(x => x.FromThisAssembly().SelectAllClasses()
.InheritedFrom<BaseEntity>()
.BindWith(new GenericArgumentBindingGenerator(typeof(IExtract<>))));
Run Code Online (Sandbox Code Playgroud)
其中GenericArgumentBindingGenerator定义为:
public class GenericArgumentBindingGenerator : IBindingGenerator
{
private readonly Type m_Generic;
public GenericArgumentBindingGenerator(Type generic)
{
if (!generic.IsGenericTypeDefinition)
{
throw new ArgumentException("given type must be a generic type definition.", "generic");
}
m_Generic = generic;
}
public IEnumerable<IBindingWhenInNamedWithOrOnSyntax<object>> CreateBindings(Type type, IBindingRoot bindingRoot)
{
if (type == null)
throw new ArgumentNullException("type");
if (bindingRoot == null)
throw new ArgumentNullException("bindingRoot");
if (type.IsAbstract || type.IsInterface)
{
return Enumerable.Empty<IBindingWhenInNamedWithOrOnSyntax<object>>();
}
var bindings = new List<IBindingWhenInNamedWithOrOnSyntax<object>>();
IBindingWhenInNamedWithOrOnSyntax<object> binding = bindingRoot
.Bind(typeof(IExtract)) // you maybe want to pass typeof(IExtract) to constructor
.To(m_Generic.MakeGenericType(type));
bindings.Add(binding);
return bindings;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3963 次 |
| 最近记录: |