Entity Framework CTP5 and Ninject as my IOC - entity-framework

Is it possible in Entity Framework CTP5 to construct retrieved persisted entities via an IOC container?
I'm using Ninject and it's tied in fine with MVC, but I need to inject some services into my domain objects when they are constructed for some business rules.
I'd rather do this using constructor injection than method or property injections.

I'm not sure what, exactly, you're trying to accomplish here, but EF has almost no extensbility points. The best you can do is hook into the ObjectMaterialized event fired by ObjectContext. In CTP5, you need to cast your DbContext like so in the constructor for your DbContext:
((IObjectContextAdapter)this).ObjectContext.ObjectMaterialized +=
this.ObjectContext_OnObjectMaterialized;
And then implement your function ObjectContext_OnObjectMaterialized(object sender, ObjectMaterializedEventArgs e). You will be able to access your object, which unfortunately has already been materialized. Depending on your needs, you might be able to hack in some interesting behavior here.
BTW, this sentence makes no sense to me:
I need to inject some repositories into my domain objects when they are constructed for some business rules.
Doesn't this go against Persistence Ignorant Domain Objects?

I tend to do the inverse of what you are trying to do. I make my domain objects as ignorant as possible (they are essentially property bags). When you need to perform some sort of action, like send an email, then I would use a service for that and have the method take in the domain object it needs to perform the action on. In this case, you would simply need to inject services into various parts of your application (which is much simpler to accomplish with Ninject).

I think EF code first CTP 5 can be of some help. It honours IValidatableObject interface, which takes ValidationContext object as an argument. The ValidationContext is a ServiceLocator so you should be able to get the instance of the IoC container using the validationContext object. (This is just my initial thought, I haven't tried anything though). Sorry, if my English is not very understandable.
Update
Sorry, just after I posted this comment I realized that the question is quite different than what I understood. So, I did try few things myself, and after some hit and trial and much more googling I was able to get somewhere. I was planning to post the answer here, but then thought against it, since the answer would be very long. So, I did post this blog instead.
http://nripendra-newa.blogspot.com/2011/02/entity-framework-ctp5-injecting-with.html
May be this might help some googlers searching for the same. Hope I got the question right this time.

Related

Is there a DataServiceContext.Set(type) equivalent to DbContext.Set(type)

I have recently created a pretty robust API built around Entity Framework's DbContext. I am using a lot of metadata programming and taking advantage of the fact that I can get my data with a call like DbContext.Set(typeof(Customer)). Only, in my API I do not know at compile time what type I will be passing to the Set method. This is working very well with EntityFramework and I would like to add another layer abstraction and have it work with both EntityFramework or DataServiceContext. So, I really have two questions.
Firstly, and more specifically, is there a DataServiceContext (i.e. odata/wcf) equivalent to the DbContext.Set(type) method?
Secondly, and more generally, is there a good resource that compares the APIs provided by DbContext with DataServiceContext?
EntityFramework and DataServices client API should not be mixed. Even though they look similar they are not. DbSet represents entity set. I don't think there is a strong contract around entity sets in DataServiceContext. Instead the name of the entity set is passed to methods that need to know this (e.g. look at DataServiceContext.AddObject() or DataServiceContext.CreateQuery() methods) as strings. In some sense it makes it much easier to program the DataServiceContext dynamically. On the other hand you still need to know what is on the other side of the pipe (i.e. the server). As said above WCF Data Services and EntityFramework are different technologies (even though they can work together) and their APIs, though similar, serve different purposes. Therefore comparing them would be like comparing apples to oranges.
The DbContext API in the client side is not the same from DbContext on server side. The main goal is to expose the data and model, which can be done pretty well. I think you may be overengeneering your app, since WCF Data Services can provide enough funcionalities.
Here is a link from Ladislav Mrnka, who is very good at entity framework, he shows how you could expose your robust api with WCF Data Services.
Implement WCF Data Service using the Repository Pattern

Entity Framework and ObjectContext references

I am playing around with Entity Framework to see how it can be used in a new project I am working on. I put my edmx file in a class library so the Entities (and database access) can be used in multiple places. Currently I have a web project and a console project both referencing the class library.
One of my Entities has a Partial class defined with a static method. The purpose of the method is to accept some parameters and create one or more instances of the specific class. My first version of the method created an ObjectContext instance, created the Entity class (or classes), and returned the Entities to the calling method. The calling method then updated some properties and tried to save the Entities using a new ObjectContext instance. Obviously this did not work because the Entities were bound (correct term ??) to the Context created within the static method.
After some research, I modified the static method to also accept an ObjectContext reference to ensure that all the Entities where created and then later on manipulated and saved using the same Context. This works fine but the design just feels wrong.
Assuming that my one static method may grow into many more, or that my app (especially the web app) would probably benefit from additional layers (DAL or even a Service Layer), does it make sense for all these classes to require an ObjectContext parameter?
I have read on many postings that creating an ObjectContext via a Singleton pattern is a bad idea because "many clients would use the same object". My problem with that is I do not see how that is possible. In a local console app there is only a single user running the app. In a web app there would only be a single user on each request. Where is the user sharing problem? Not a single article/posting mentioned it...but where they referring to a Singleton pattern storing the object instance in the Application context?
I have also seen postings focused on web usage and storing the object instance in the users Session object via the HttpContext object. This makes sense but does not seem to address non-web usage.
I think that whatever solution is appropriate (static methodm, Factory object, etc.) would most likely be implemented in my class library so obviously it needs to support both web and non-web solutions. Maybe check for HttpContext to determine what environment it is running in.
I was hoping http://www.west-wind.com/weblog/posts/2008/Feb/05/Linq-to-SQL-DataContext-Lifetime-Management would be informative but I am having a hard time wrapping my head around the post and the example code seems like overkill for instantiating and sharing a simple object. (Although I am sure I am just not getting it...)
Any thoughts are appreciated.
Thanks.
The issue is not that “many clients would use the same object.” The issue is that the ObjectContext is intended to be a single unit of work. If you use it for many different units of work, you will find that there are a number of problems.
Memory usage will grow and grow.
Your application will become slower as object fixup has to do increasing amounts of work.
Multithreading won't work
The solution is to use the ObjectContext in the manner it is intended, namely, as a single unit of work.

Custom Membership Provider and Domain-Driven-Design

I have a concern where I am writing a custom membership provider, but I'm not sure where to put it. I don't really have any code to show you, but basically the provider needs access to System.Web.Security in order to inherit the class, but it also needs data access (i.e. a connection string + LINQ to SQL) to do simple tasks such as ValidateUser.
How can I write a membership provider that adheres to the principles of DDD that I've read about in Pro ASP.NET MVC2 Framework by Apress? My one thought was to write another class in my domain project which does all the "work" related to database stuff. In essence I would have double the number of methods. Also, can this work with dependency injection (IoC)?
Hope this isn't too general ...
Look forward to the hive-mind's responses!
Edit: I just noticed in a default MVC2 project there is an AccountController which has a wrapper around an IMembershipService. Is this where my answer lies? The AccountController seems to have no database access component to it.
Asp.net user management features are super invasive.
They even spam database with profile tables and what not.
When I had to implement users management of my application, I successfully avoided all that mess and still was able to use asp.net in-built roles, user identities etc. Moving away from all that though cause my domain is getting smart enough to decide what can be seen and done so it makes no sense to duplicate that in UI client.
So... yeah. Still have zero problems with this approach. Haven't changed anything for ~4 months.
Works like a charm.

What's the best POCO status tracking strategy? (EF)

So I was reading about Entity Framework and based on my agile development scenario I decided to go with POCO objects.
But now I'm having some extra problems I don't know how to get away with.
I'm working with RIA services and Silverlight so when I'm going to Save an object of the server side I have to attach the object to an ObjectContext. The thing is that I must then change the ObjectState to Added or Modified.
So my question is what's the best approach to really know what state to change it to. I saw in Julia Lerman's book that she uses a State attribute in her POCO objects and she takes care managing that state on the client side before sending the object to the server. That state then is used to change the real EntitySate once attached.
I've also seen other samples where the Insert implementation checks on the Key of the Entity (object) to know whether it is new or not. For example, if ProjectId in my Project entity is 0 (zero) I know it has to be a new object.
To be honest I don't like any of those approaches because in both cases my developers have to do some extra-work to actually save the object.
I'd like the know pros and cons of both solutions and hopefully a new (better) solution I'm still not seing.
You can still have self tracking entities and poco. In visual studio if you search the community templates there is a self tracking poco template. this is what you want to use. If you can find the template look for your entities using Ientitywithobjecttracker.
http://msdn.microsoft.com/en-us/library/dd456848.aspx

Extending Entity Framework

I'm developing a program which allows users to input some information which then gets stored and dynamically creates an image based on it.
I was going to use the Entity Framework to do the work with the data, but then I obviously need a way to generate the image. My thinking was that the "correct" way to do this was to somehow extend the data entity to include a function call like "CreateImage", or alternatively, to create a separate class not in the EF called "DataImage" which would have a "generate" method.
Extending the EF seems the "pure" way to do this, but I'm not sure how or if it's more practical than using the separate class.
Any thoughts on the best way to do this and how to do it using EF?
Putting this functionality in the EF would be a major violation of SRP. Breaking SRP has cascading negative effects as your application grows.
The approach you most likely want to take instead is a totally separate, encapsulated image generation service which takes interfaces that your EF entities implement. This decouples your image service from your data access completely; you get complete testability and zero dependencies right away.