[英]Unity resolving constructor with ICollection<IMyInterface> dependency
我正在编写规则引擎。 我有一个接口IRule
,它实现了许多规则。 此外,我有一个RuleExecutor
,它注入了IEnumerable<IRule>
依赖项。
我希望 Unity 注入一个带有所有绑定实现的IEnumerable<IRule>
,但不幸的是它不起作用。
这是我的配置:
container.RegisterType<IRule, RuleA>("a");
container.RegisterType<IRule, RuleB>("b");
container.RegisterType<IRule, RuleC>("c");
container.RegisterType<IRule, RuleD>("d");
container.RegisterType<IRule, RuleE>("e");
container.RegisterCollection<IRule>();
container.RegisterType<IRuleExecutor, RuleExecutor>(new InjectionConstructor(typeof(IEnumerable<IRule>)));
注册集合是这样的:
public static class UnityExtensions
{
public static void RegisterCollection<T>(this IUnityContainer container) where T : class
{
container.RegisterType<IEnumerable<T>>(new InjectionFactory(c => c.ResolveAll<T>()));
}
}
解决时我收到以下异常消息:
RuleExecutor 没有接受参数 () 的构造函数。
Unity 怎么可能做到这一点?
Unity 将自动将所有命名实例注入IEnumerable<T>
。 这是一个工作示例。
using System.Collections.Generic;
using Unity;
class Program
{
static void Main(string[] args)
{
var container = new UnityContainer();
container.RegisterType<IRule, RuleA>("a");
container.RegisterType<IRule, RuleB>("b");
container.RegisterType<IRule, RuleC>("c");
container.RegisterType<IRule, RuleD>("d");
container.RegisterType<IRule, RuleE>("e");
container.RegisterType<IRuleExecutor, RuleExecutor>();
var executor = container.Resolve<IRuleExecutor>();
}
}
public interface IRule { }
public class RuleA : IRule { }
public class RuleB : IRule { }
public class RuleC : IRule { }
public class RuleD : IRule { }
public class RuleE : IRule { }
public interface IRuleExecutor { }
public class RuleExecutor : IRuleExecutor
{
public RuleExecutor(IEnumerable<IRule> rules)
{
// Rules RuleA through RuleE are injected here...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.