Reputation: 1464
Is there a way to implement dependency injection with Entity framework and lazy loading?
I am aware of method when you are hooking to ObjectStateManagerChanged
, but I'd like to use constructor injection instead, and keep my model entities unaware of any IOC containers. (Lets say I have separated BLL and DAL and want to keep my BLL with least external dependencies possible).
Thank you.
Upvotes: 2
Views: 1941
Reputation: 172646
Prevent from using dependency injection in your entities altogether. Take a look at this SO question for instance.
Try using the command / handler pattern for writing business operations. By defining one generic interface, you have great extensibility and the power to implement security checks by implementing a simple decorator.
To prevent UI developers from accessing data they shouldn't be accessing, write one (or multiple) decorators that wrap command handlers (and query handlers) and prevent from returning entities with lazy loading abilities from your business layer. Instead return DTOs. This way the business layer has full control.
Upvotes: 3
Reputation: 364269
You cannot use constructor injection with EF. EF always use default constructor when materializing entity from database records. The only option you have in this case is using ObjectMaterialized
event of ObjectContext
and use properties in your entity to pass your initialization data.
You should follow @Steven's comments to implement logic you need.
Upvotes: 1