Search code examples
c#unity-container

Is it possible to registry class , unity container ,c#


I'd like to use unity container to implement a singleton design.

for example:

create the singleton:

container.RegistryInstance<IClass>(new Class())

get the singleton instance:

container.Resolve<IClass>()

Can I do the same but with a class and not with interface?

for example:

create the singleton:

container.RegistryInstance<Class>(new Class())

get the singleton:

container.Resolve<Class>()

Solution

  • Sure. In that case, you do not need to provide a type argument to RegistryInstance.

    From http://unitycontainer.org/tutorials/registration/instance.html:

    The simplest instance registration does not require any additional parameters other than instance itself:

    var instance = new Service();
    
    container.RegisterInstance(instance);
    

    Resolving type Service like this container.Resolve<Service>() will return an instance of the Service object we registered.