TinyIOC和多个用户指定的工厂类型
本文关键字:工厂 类型 用户 TinyIOC | 更新日期: 2023-09-27 18:15:13
我目前正在尝试使用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
基本上像这样的解析器,你必须自己做多重注册位-即,而不是直接注册类型,你必须注册"注册的服务列表"。这是一种痛苦。
如果你不需要通过构造函数注入服务,我建议你只使用内置的,它实际上是非常好的。
Update:终于找到了一些我写的代码来解决autofacc中的类似问题: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