我目前正在尝试使用TinyIOC连接自定义ReactiveUI IMutableDependencyResolver。我正在努力解决ReactiveUI希望在用户指定的工厂注册多个接口实现的事实。哪个TinyIOC似乎不支持。
我的实现似乎每次重新调用寄存器时都会覆盖以前的注册。有什么建议吗?
#region IMutableDependencyResolver implementation
public void Register(Func<object> factory, Type serviceType, string contract = null)
{
TinyIOC.TinyIOCContainer.Current.Register(serviceType, (a, b)=>
{
var result = factory();
return result;
}, contract);
}
#endregion
答案 0 :(得分:1)
基本上对于像这样的解析器,你必须自己做多个注册位 - 即不是直接注册类型,而是必须注册“注册的服务列表”。这有点痛。
如果你不需要通过构造函数注入服务,我建议你只使用内置的服务注册,它实际上是非常好的。
更新:最后找到了我编写的一些代码来解决AutoFac中的类似问题: var builder = new ContainerBuilder(); var container = default(IContainer);
#region Don't actually read this terrible code
// NB: This garbage exists in order to work around the fact that
// Autofac doesn't support multiple registrations for the same type
// (i.e. GetAllServices), but RxUI relies on it.
var registrations = new Dictionary<Tuple<Type, string>, List<Type>>();
RxApp.ConfigureServiceLocator(
(t, s) => s != null ? container.ResolveNamed(s, t) : container.Resolve(t),
(t, s) => {
var type = typeof(IEnumerable<>).MakeGenericType(t);
var ret = (IEnumerable<Type>)container.ResolveNamed<IEnumerable<Type>>(type.FullName);
return ret.Select(x => Activator.CreateInstance(x)).ToArray();
},
(c, t, s) => {
// NB: This is the hackiest hack of hack to work around a bug in RxUI
if (container != null) return;
var pair = Tuple.Create(t, s);
if (!registrations.ContainsKey(pair)) registrations[pair] = new List<Type>();
registrations[pair].Add(c);
});
foreach (var kvp in registrations) {
if (kvp.Value.Count == 1) {
var reg = builder.RegisterType(kvp.Value[0]).As(kvp.Key.Item1);
if (kvp.Key.Item2 != null) reg.Named(kvp.Key.Item2, kvp.Key.Item1);
} else {
var type = typeof(IEnumerable<>).MakeGenericType(kvp.Key.Item1);
builder.RegisterInstance(kvp.Value).As<IEnumerable<Type>>().Named<IEnumerable<Type>>(type.FullName);
}
}
#endregion