Is there any potential problem in setting datacontext as property like this:
repository
public Repository() { public DataContext dc {get;set;} public GetOrders(int id) { ...from dc.Orders...} }
service layer:
public GetNewOrders() { .... Repository rep=new Repository(); using {DataContext dc=new DataContext()) { rep.dc=dc; rep.GetOrders(id); } }
In DDD, you’re missing the bigger picture here by referencing the concret classes. You are not interfacing between the Repository and ‘Services layer’ by best practices. If you must have DataContext injected into the Repository, I would recommend refactoring to:
The better solution would be to let the Repository handle the DataContext on its own – keeping the seperation of concert valid by masking the underlying requirements:
If you must keep control of the DataContext (or another class) yourself (perhaps you want to keep a static reference around, or change settings based on an WebRequest, etc), you you will need to use a ‘Factory’.
The factory would look something like this:
That way, you have full control over how the instance of DataContext is controlled outside and away from your ‘Services’ layer. So, you would use this DataContextFactory like the following:
‘How to access the IRepository?’ you may ask?
Your services layer would do something like:
Or, you would inject it into the constructor of your service using your favorite flavor of Inversion of Control container like so:
If you are not fimilar with the service locator concepts, check out Castle Windsor as it Encapsulates just about all your needs.