IUnityContainer.RegisterFactory例子

使用Unity的InjectionFactory进行依赖注入遇到如下提示:

'InjectionFactory' is obsolete: 'InjectionFactory has been deprecated and will be removed in next release. Please use IUnityContainer.RegisterFactory(...) method instead.

提示InjectionFactory将被淘汰的注入代码:

var container = new UnityContainer();
container.RegisterType<IAnimal, Cat>("Cat", new InjectionConstructor());
container.RegisterType<IAnimal, Dog>("Dog", new InjectionConstructor());

container.RegisterType<List<IAnimal>>(
    "AnimalList",
    new InjectionFactory(
        m => new List<IAnimal>
        {
            m.Resolve<IAnimal>("Cat"),
            m.Resolve<IAnimal>("Dog"),
        }
        )
);

改为RegisterFactory之后的注入代码:

container.RegisterFactory<List<IAnimal>>(
    "AnimalList",
    m => new List<IAnimal>
    {
        m.Resolve<IAnimal>("Cat"),
        m.Resolve<IAnimal>("Dog"),
    }
);

两段代码比较,区别在于将"RegisterType"方法替换为"RegisterFactory"方法,并将InjectionFactory这层的wrapper去除即可。

比较下RegisterType和RegisterFactory的构造函数,也可以看出diff:

IUnityContainer RegisterType<T>(this IUnityContainer container, string name, params InjectionMember[] injectionMembers);
InjectionFactory(Func<IUnityContainer, object> factoryFunc);

IUnityContainer RegisterFactory<TInterface>(this IUnityContainer container, string name, Func<IUnityContainer, object> factory, IFactoryLifetimeManager lifetimeManager = null);