Craig
Craig

Reputation: 18694

Singleton, Static and IoC

I am attempting to change my Reference data service layer, to a static implementation, and applying the singleton pattern. Reason is, I think the reference service can be static for performance improvements (All share the same 'instance' - I think?)

I have a layered app. UI->Service->Logic->Data

However, I use IoC, and think there is a clash here. I use Unity as my IoC container. I'm starting the conversion by adding a static instance, and a public Instance, which handles the instance.

However, I'm not sure what to do with my constructor. I (Unity) currently inject my Reference data logic class into the constructor...

public class ReferenceDataService : IReferenceDataService
{

    private static ReferenceDataService instance;

    IReferenceDataLogic _refDataLogic;
    ObjectCache cache = MemoryCache.Default;

    public ReferenceDataService(IReferenceDataLogic logic)
    {
        _refDataLogic = logic;
    }

    public static ReferenceDataService Instance {

        get
        {
            if(instance != null) return instance;
            lock(new object())
            {
                instance = new ReferenceDataService();
            }
            result instance;
        }
    }
}

But I think I need to remove this constructor, so that in my UI code, I can get data but saying:

var MyReferenceDataList = ReferenceDataService.Instance.GetMyReferenceDataList(type);

Would I need to make the Logic and Data access layer classes static as well? Which means I could never really unit test this.

Upvotes: 1

Views: 1089

Answers (1)

Fran
Fran

Reputation: 6520

You should be able to just tell your container to give you back a single instance. I'm not familiar with Unity, but with Castle Windsor you just set the lifestyle to singleton

container.Register(Classes.FromThisAssembly()
   .BasedOn(typeof(IProvideWellKnownData))
   .WithServiceAllInterfaces()
   .LifestyleSingleton());

Upvotes: 1

Related Questions