How to register services for DI with Unity

Stesvis 1,041 Reputation points
2021-11-04T16:28:30.333+00:00

I am a little bit stuck on registering services with Unity in a MVC 5/EF6 app (not .net core).
I have a bunch of services that "do work", and they are injected in Controllers and sometimes in other Services.

This is how i've always registered my services, using RegisterSingleton:

private void ConfigureServices(IServiceCollection services, IUnityContainer unityContainer)
        {
            // Services
            unityContainer.RegisterSingleton<IServiceA, ServiceA>();
            unityContainer.RegisterSingleton<IServiceB, ServiceB>();
            unityContainer.RegisterSingleton<IServiceC, ServiceC>();

            unityContainer.RegisterSingleton<DbContext, ApplicationDbContext>();
        }

Now after some reading, i am a bit confused. Is this the right approach or should I register them using RegisterType?
Mostly, what criteria do you use to decide when to use one or the other?

How do you register your services?

Thanks!

Developer technologies | .NET | Other
Developer technologies | C#
{count} votes

1 answer

Sort by: Most helpful
  1. AgaveJoe 30,126 Reputation points
    2021-11-04T18:29:25.693+00:00

    A singleton is a application scoped object where every client request uses the same object instance. With that said, it is unusual for all services in a web application to implement a singleton lifetime. Typically, you'll have a mixture of service lifetimes because not all services work the same way.

    I recommend reading the Unity scope documentation to understand what Unity lifetime features are available. Then pick the an appropriate lifetime for each of your services.

    Class TypeLifetime


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.