1
votes

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.

1
Do you need to do any of that. Can't you use you original implementation and just tell unity to create a single instance? - Fran
I'm not sure, @Fran - I'll look into that. - Craig
It looks like you've educated me here. In my Unity container, can I simply do this: myContainer.RegisterType<IMyObject, MySingletonObject>(new ContainerControlledLifetimeManager()); - which means the class will be treated as a singleton? I'm guessing I need to change the Service layer class, the Logic and the database classes? - Craig
You should prefer doing this instead of using the Singleton Pattern, because that pattern complicates testing and disallows your class to be easily intercepted or decorated. Besides, your locking model is completely flawed. Unity (or any container for that matter) will ensure that at most one instance is created, when configured this way. - Steven
Agree with @Steven. Just register your class with ContainerControlledLifetimeManager and don't change anything else! - Backs

1 Answers

1
votes

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