开发者

Ninject and private constructors

开发者 https://www.devze.com 2023-04-08 09:48 出处:网络
We\'re using Ninject for IOC. All of our Repository objects can (and should be) mocked for unit testing.I\'d like to enforce that all developers code only to interfaces when interacting with Reposito

We're using Ninject for IOC.

All of our Repository objects can (and should be) mocked for unit testing. I'd like to enforce that all developers code only to interfaces when interacting with Repositories. For this, I'd like to make the constructors private and create static accessor factory methods for construction:

public class SomeRepository : ISomeRepository
{
 private SomeRepository()
 {
 }
 public static ISomeRepository Create()
 {
   return StandardKernel.Get<ISomeRepository>();
 }
}

Problem lies in this开发者_如何学运维: how do I have Ninject create the actual object? I have repository interface and class in the same project


We're ultimately going with the following:

public class SomeRepository : ISomeRepository
{
 private SomeRepository()
 {
 }
 public static ISomeRepository CreateForIOC()
 {
   return new SomeRepository();
 }
}

and during module loading, we're mapping the StandardKernel's ISomeRepository interface to CreateForIOC() method.

This does not stop developers from calling CreateForIOC directly, but at least forces them to a) code to an interface, b) realize that CreateForIOC() is probably not the right method to call when instantiating the object and at least ask a question about it from a lead developer


Instead of either the private constructor or the factory method, why not just have Ninject provide the the concrete repository to any objects that need it?


It looks like you're trying to use a singleton pattern. In general, the singleton pattern is considered an anti-pattern, largely because it hinders unit testing. Dependency injection allows you to create singletons via configuration without having to use the singleton pattern.

I would suggest that you instead, simply configure Ninject to create a single instance of your app without the private constructor.

0

精彩评论

暂无评论...
验证码 换一张
取 消