c# - How should I inject behaviour into an Entity -
i exploring utilize of entity framework database first , trying understand if should inject behavior entity, , if so, best technique doing this. typically have done in past avoid anemic domain objects. couple utilize cases inject specification entity (specification pattern/define composable business rules) or perhaps inject ninject implemented mill root entity binding of implementation determined strategy/factory method @ point of use) illustration below, utilize ioc inject in isomethingspec implementation.
class foo { void dosomething() { if(somethingspec.satisfiedby(this) { } } }
may ask, should consider different pattern associating behavior entity? or if reasonable, using partial classes/property , method injection best alternative using ef5 database first?
this first post, hope it's format not far off mark. posted have looked @ other questions similar not determine consensus on best practice associating behavior domain objects /ef entities.
i utilize specification pattern entity framework filter info retrieved database. think can utilize same approach , adapt needs.
you can utilize di container inject specifications , other objects may need. first step define contract specification objects, this:
public interface ispecification<t> t : class { expression<func<t, bool>> getexpression(); bool issatisfiedby(t entity); }
a generic specification object can defined this:
public class specification<t> : ispecification<t> t : class { private expression<func<t, bool>> expression; public expression<func<t, bool>> getexpression() { homecoming expression; } public specification(expression<func<t, bool>> expression) { this.expression = expression; } public bool issatisfiedby(t entity) { var query = (new[] { entity }).asqueryable(); homecoming query.any(this.expression); } }
and can alter foo class this, can inject dependency using di/ioc container:
public class foo() { public ispecification<foo> specification { get; private set; } public foo(ispecification<foo> specification) { this.specification = specification; } public void dosomething() { if(specification.satisfiedby(this)) { //... } } }
creating , using specification:
// illustration - create 1 specification expression<func<foo, bool>> look = ....; ispecification<foo> foospecification = new specification<foo>(expression); // using specification linq var entities = dbcontext.foos.where(foospecification.getexpression()); // performing validation var foo = new foo{ // .... }; if(foospecification.issatisfiedby(foo)) { // something.... }
more details here:
http://ruijarimba.wordpress.com/2011/06/05/entity-framework-and-t4-generate-specification-objects-for-your-entities/
c# .net entity-framework design-patterns dependency-injection
No comments:
Post a Comment