Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Register null as instance in Unity container

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?

like image 391
v0id Avatar asked Jul 09 '12 09:07

v0id


People also ask

How do I register a type with Unity container?

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.

When should I use ContainerControlledLifetimeManager?

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 .

What is Unitycontainer C#?

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.

What is RegisterType?

RegisterType a type mapping with the container, where the created instances will use the given LifetimeManager. Namespace: Microsoft.Practices.Unity.


2 Answers

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.

like image 189
mrwaim Avatar answered Oct 13 '22 21:10

mrwaim


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>()));
like image 20
cynic Avatar answered Oct 13 '22 22:10

cynic