I got some static classes with extension methods which add 'business logic' to entities using the repository pattern.
Now sometimes i need to create a new IRepository
in these extension functions.
I'm currently working around it by accessing my Ninject kernel through the object I'm extending, but it's really ugly:
public static IEnumerable<ISomet开发者_JAVA技巧hing> GetSomethings(this IEntity entity)
{
using (var dataContext = entity.kernel.Get<IDataContext>())
return dataContext.Repository<ISomething>().ToList();
}
I could also make a static constructor, accessing the Ninject kernel somehow from a factory, is there already infrastructure for that in Ninject 2?
Does anybody know a better solution? Does anybody have some comments on this way to implement business logic.
On the issue of extension methods and how they get stuff. You have two approaches:
Service Location - have a global Kernel and drop down to Service Location (which is different from Dependency Injection). The problem here though is that your Entity (or its extensions) should not be assuming its context and instead demanding it
As you are an extension method have the thing you're extending pass you what you need
As you've more or less guessed, this (Having a global Kernel that becomes the dumping ground) is something that Ninject tries to dissuade you from. In general, the extension for whatever the you're using (e.g., MVC or WCF) will provide something if its appropriate. For example, the WCF extension has http://github.com/ninject/ninject.extensions.wcf/blob/master/source/Ninject.Extensions.Wcf/NinjectServiceHost.cs
The larger issue here is that dependencies like this should probably not propagate down to the Entity level - it should stay at the Service level and be propagated from there (using DDD vocabulary).
You may find this answer by me interesting as it covers this ground a bit (more from a Ninject techniques that an architectural concepts perspective)
精彩评论