So the story goes like this:
I have singleton class (a.k.a ServiceLocator) which you can get the instance using the "CreateInstance()" method. At the same time, we added Unity into our application and configured it using the standard configuration file.
The problem started when i was trying to map the interface IServiceLocator
to get the instance of ServiceLocator
and register it in the unity configuration file. As you probably guesses, ServiceLocator DOES NOT have a public constructor (i.e, singleton), hence, unity cannot create it when I do unity.resolve<IServiceLocator>()
….
My question: Is there any way to tell Unity (through the configuration file) to use CreateInstance()
instead of trying to execute the default constructor? If not, if you have any other idea what else can be done, I would appreciate to hear it.
Please don't suggest me to change the constructor to public, assume I can't do it for now.
Best Answer
You'd better create manually UnityContainer and inject it into your service locator:
this is a simplified version of prism extension to unity. see more detailed sources of modulesmanager class in prism. app starts with Run method. You create container and register your servicelocator in it. Wile registering, UnityContainer creates instance of it and pass itself into ctor:
then, using SetServiceLocatorProvider method you assign to Instance property instance of servicelocator class, that has reference to unity container within. Such solution also gives abstraction of concrete DI container. And you can reference to your service locator from anywhere in your code. 1) Injectiong into constructor
or using static class:
ps: IServiceLocator interface, which is an abstraction of concrete implementation of DI container:
its methods wraps concrete container's methods, for example:
Hope - it helps!