Register null as instance in Unity container

unity container register instance
unity dependency injection
unity dependency injection console application c#
unity container register factory example
unity container documentation
unity container resolve
unity container github
unity container resolve with parameters

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?

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>()));

Register and Resolve using Unity Container, Learn how to register and resolve types using unity container. public class Driver { private ICar _car = null; public Driver(ICar car) { _car = car; } public then we will have to pass an instance of a class which implements the ICar interface,  The RegisterInstance method registers an existing instance with the container. You specify the instance type and optional lifetime in the parameter list. The container will return the specified existing instance for the duration of the specified lifetime. Unity container offers several overloads to simplify registration syntax.

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.

Resolving collections of Objects of a Particular Type, Unity supports creating multiple registration of the same type by adding a name to container.RegisterInstance<IPrinter>(printer); // default printer container. an array containing only types registered with nondefault (other than null ) names​. Unity Container: Register and Resolve . In the previous section, we installed Unity framework in our console project. Here, we will learn how to register type-mapping and resolve it using the unity container. As we learned in the IoC container chapter, every container must provide a way to register and resolve dependencies.

For 'nice to have' dependencies you should use property injection instead of ctor injection. Config would look something like this:

public class MyRepository
{
  public ICacheProvider Cache { get; set; }
}

container.RegisterType<MyRepository>(new InjectionProperty("Cache", typeof(ICacheProvider)));

That would inject an implementation of ICacheProvider into a property named Cache of your MyRepository. As you would have to implement null checks wherever you make a call to the Cache property inside your repository class I would go with @dtryon's proposal and implement a NullCacheProvider. That is far more convenient and less error prone.

Interface IUnityContainer, Register an instance with the container. null ) container uses PerContainer  Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Register null as instance in Unity container. 0

Simplest Non-Obsolete solution

Calling RegisterType with an InjectionFactory is currently obsolete, so here is the currently recommended approach:

container.RegisterFactory<ITypeToResolve>(c => null);

Flexible Extension Method

Or if you want to make an extension method to return anything you want you could do something like:

public static void RegisterFactory<TToResolve>(IUnityContainer container, Func<TToResolve> factory) => 
        container.RegisterFactory<TToResolve>(c => factory.Invoke());

Then to consume that you'd do:

container.RegisterFactory<ITypeToResolve>(() => new MyTypeToResolve());

[PDF] DepenDency InjectIon wIth UnIty, Configuring the Unity Container to Support Interception locator as a registry that you can look up an instance of an object or service that if (container != null)​. I would like to tell unity when resolving that list to create exactly N instances of Worker. Anyone can help? I tried the following: Receiving an array instead of a List and registering like so: for (int i = 0; i < N; i++) { this.Container.RegisterType<IWorker, Worker>(i.ToString()); }

I've ended with implementing some sort of a NullObject pattern on my optional dependency:

public class NullCacheProvider : ICacheProvider
{
    // …
}

And in the base repository class i have check:

public class BaseRepository
{
    protected readonly ICacheProvider CacheProvider;
    protected readonly bool ShouldUseCache;

    protected BaseRepository(IDataContext context, ICacheProvider cacheProvider)
    {
        CacheProvider = cacheProvider;
        ShouldUseCache = 
            CacheProvider != null && !(CacheProvider is NullCacheProvider);
    }
}

Then in a projects where i don't need a cache i have configured Unity like this:

container
    .RegisterType<IDataContext, MyDataContext>(new PerResolveLifetimeManager(), new InjectionConstructor())
    .RegisterType<ICacheProvider, NullCacheProvider>() 
    .RegisterType<IMyRepository, MyRepository>();

The point of all this is that the particular repository may act differently depending on fact of existence the optional dependency. It may seem as some architectural flaw but the solution meets my requirements.

unitycontainer/microsoft-dependency-injection, NullReferenceException: Object reference not set to an instance of an object. in fixes registration.type null issues unitycontainer/container#68. Simplest form of a contract is a registration without a Name (the Name is null). This type of registration is called default and in some cases is used as a prototype during resolution of Generic types (hence name default). A contract could have a Name. The Name could be any arbitrary string of one or more characters.

A small introduction to Unity Container, Dependency Injection is one way to implement Inversion of Control. </summary​> public static void Register<TFrom, TTo>() where TTo : TFrom Assert.IsNotNull​(_instance, "Instance of object Initializer should not be null."); Registration is how you control Unity to do it 'Your' way. When you register a Type, you are instructing Unity to create and initialize an instance of that Type in a very particular way. You also instruct Unity how to deal with the crated instance during its lifetime.

Managing Dependencies Between Components Using the Prism , For example, when using the Unity Application Block (Unity) as the container, They both register instances with the container. Orders.MoveCurrentTo(null); }. container.RegisterInstance<IEmail>(new Email("To Name", "to@email.com")); That will register the supplied instance as a singleton for the container. Then you just resolve the service: container.Resolve<OperationEntity>(); And because you are resolving a concrete type, there is no registration required.

Dependency Injection Using Unity, Unity acts as a container for this object creation and dependency It makes use of Unity to register an instance of any type coming to it. Unity Container: Constructor Injection . In the previous chapter, we learned about registering and resolving types using Unity container. Here, you will learn how Unity container performs constructor injection. Construction injection is a type of Dependency Injection where dependencies are provided through a constructor.

Comments
  • Why have an optional dependency? Just implement an ICacheProvider that does nothing.
  • @dtryon, yes. The only option that came to my mind is to create NullObject implementation of the ICacheProvider.
  • Looks like what's i'm asking for. Have not enough time right now to check out if this solution plays nice with PerResolveLifetimeManager, but i believe it does.
  • IMO it is really bad that Unity even contains a OptionalParameter class that allows you to inject null values into constructors. This is really bad application design and the framework should prevent users from doing this.
  • FYI, order matters when defining the parameters here.
  • Didn't work for me, I got Exception is: InvalidOperationException - The type RazorEngineService does not have an accessible constructor. when I configured IRazorEngineService to return null. Not sure why yet; I hadn't mentioned the concrete..
  • Worked perfectly! Thanks!
  • Nice. Easy but this is obsolete now.
  • If you used the Null Object Pattern, you should mark Sabastian as answer, not cynic. Also note that it is better to merge this answer with your question.
  • In your final implementation, your BaseRepository now depends on the ICacheProvider implementation NullCacheProvider which is a bad thing. There is no need for the BaseRepository to know anything about implementations, that's the idea behind the Null Object pattern. Instead, prevent callers from injecting null in the cacheProvider parameter. When you implemented this default cache provider correctly, you don't need the ShouldUseCache, which makes the code simpler and more maintainable.
  • @Steven, in general i would agree with you. But in the case the Repository must know whether it has ICacheProvider or not, and with this knowledge modify own behavior (change fetch plan and use cache to load entities). So it is not canonical implementation of the Null Object pattern, but only workaround as i had no better ideas.
  • Implementing the Null Object pattern does not mean that this implementation does nothing, but that it implements "neutral behavior". In your case the neutral behavior would be an implementation that allows your Repository to work without having to worry about whether entities are cached or not. Take a step back and look at your design.