C# Unity Replace InjectionFactory by RegisterFactory Example
When you use RegisterType or RegisterInstance combined with InjectionFactory in old version of Unity, the following complier warning will be displayed:
'InjectionFactory' is obsolete: 'InjectionFactory has been deprecated and will be removed in next release. Please use IUnityContainer.RegisterFactory(...) method instead.
The code that triggered the warning:
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"),
}
)
);
The solution is straightforward, follow the instruction and use RegisterFactory instead:
container.RegisterFactory<List<IAnimal>>(
"AnimalList",
m => new List<IAnimal>
{
m.Resolve<IAnimal>("Cat"),
m.Resolve<IAnimal>("Dog"),
}
);
The main difference of the replacement:
- Replace "RegisterType" to "RegisterFactory"
- Remove InjectionFactory wrapper
Moreover, it's easy to find the difference by comparing the declarations:
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);