Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Common Service Locator in Ninject 2

Changes in Ninject 2 say that Ninject support Common Service Locator, but how do I use it? I don't find any manual or sample.

like image 254
magol Avatar asked Sep 20 '10 10:09

magol


1 Answers

The Ninject2 download contains a CommonServiceLocator.NinjectAdapter.dll (in the 'extensions' folder of the zip file). Add this dll and the Ninject.dll to your project.

In the startup path of your application (after configuring the Ninject kernel), you can use the following code:

IKernel ninject = ...; 

var locator = new NinjectServiceLocator(ninject);

ServiceLocator.SetLocatorProvider(() => locator);

Please note that the Common Service Locator (CSL) is a library that provides an abstraction over IoC containers and contains a static facade (implementing the Service Locator pattern). It is a common interface that developers can use to prevent depending on a specific IoC implementation. The CSL is especially useful for framework developers. Application developers are better of using the dependency injection (DI) pattern. When DI is used correctly, there is no need for the use of the CSL in an application. While the CSL is more suited for framework development, even there I find the use of the CSL questionable. In believe that most of the time the use of such common interface can be removed by having a proper design.

like image 188
Steven Avatar answered Oct 04 '22 05:10

Steven