I have a repository class with optional dependency:
class MyRepository : BaseRepository, IMyRepository
{
public MyRepository(IDataContext dataContext, ICacheProvider cacheProvider = null)
: base(dataContext, cacheProvider)
{}
// …
}
The existence of cacheProvider parameter acts as strategy for the repository. I want setup Unity container like this:
Container.RegisterType<IDataContext, MyDataContext>(new PerResolveLifetimeManager(), new InjectionConstructor())
.RegisterInstance<ICacheProvider>(null) // ???
.RegisterType<IMyRepository, MyRepository>();
I.e. not pointing out particular InjectionConstructor with one parameter for MyRepository, but use default constructor with null as cacheProvider parameter.
Is there any way to do this?
Before Unity resolves the dependencies, we need to register the type-mapping with the container, so that it can create the correct object for the given type. Use the RegisterType() method to register a type mapping. Basically, it configures which class to instantiate for which interface or base class.
Use the ContainerControlledLifetimeManager when you want to create a singleton instance. In the above example, we specified ContainerControlledLifetimeManager in the RegisterType() method. So, Unity container will create a single instance of the BMW class and inject it in all the instances of Driver .
The Unity Container (Unity) is a full featured, extensible dependency injection container. It facilitates building loosely coupled applications and provides developers with the following advantages: Simplified object creation, especially for hierarchical object structures and dependencies.
RegisterType a type mapping with the container, where the created instances will use the given LifetimeManager. Namespace: Microsoft.Practices.Unity.
I found that RegisterType, instead of Register instance, supports returning null.
container.RegisterType<IInterface>(new InjectionFactory((c) => null));
This was the most straightforward way of getting an actual null
to be returned.
In the .RegisterType<IMyRepository, MyRepository>()
call, specify the InjectionConstructor with an OptionalParameter, as in
.RegisterType<IMyRepository, MyRepository>(new InjectionConstructor(
new ResolvedParameter<IDataContext>(),
new OptionalParameter<ICacheProvider>()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With