digipolisantwerp / dataaccess_aspnetcore_deprecated

Generic repository/unit of work framework for ASP.NET Core with Entity Framework.
Other
140 stars 45 forks source link

Create instance of IUowProvider in Singleton class #18

Closed anhlee24 closed 8 years ago

anhlee24 commented 8 years ago

How can i create an instance of IUowProvider?

I have a singleton class like this and need to create instance:

` public class SystemConfig : ISystemConfig

  {
    private static SystemConfig SystemConfigInstance = new SystemConfig(default(UowProvider));// problem here

   public SystemConfig(IUowProvider uowProvider)
    {
        _uowProvider = uowProvider;
   `}

    public static SystemConfig GetInstace()
    {
        if (SystemConfigInstance == null)
        {
            lock (typeof(SystemConfig))
            {
                if (SystemConfigInstance == null)
                {
                    SystemConfigInstance = new SystemConfig(default(UowProvider));
                }

            }
        }
        return SystemConfigInstance;
    }
 }
StevenVandenBroeck commented 8 years ago

A better way to make singletons is to use the dependency injection framework. Just make a normal class and register it as a singleton during Startup :

services.AddSingleton<MyInterface, MyClass>();

In this class you inject the IUowProvider via the constructor and the dependency injection framework will instantiate it, since it is also registered (as a singleton actually) :

https://github.com/digipolisantwerp/dataaccess_aspnetcore/blob/development/src/Digipolis.DataAccess/Startup/ServiceCollectionExtensions.cs

You can find more on the dependency injection framework in .NET Core docs. Look for the lifetime section

anhlee24 commented 8 years ago

Thank you! My problem resovled!