I've been using EntityFramework for a short time. Up until now I've only used the EF DBContext within discrete using blocks. I'm now trying to use request scope dependency injection. Unity seems to be the easiest, but I'm not sure if I'm using it correctly.
So far I've created a sample repository and service class (with corresponding interfaces). I register these in Unity, like so...
Public Shared Sub RegisterComponents()
Dim container = New UnityContainer()
container.RegisterType(Of IMyService, MyService)()
container.RegisterType(Of IRepository(Of MyModel), MyRepository)()
DependencyResolver.SetResolver(New UnityDependencyResolver(container))
End Sub
My repository looks like this...
Public Class MyRepository
Implements IRepository(Of EF.MyModel)
<Dependency>
Public Property Context() As MyDBEntities
Public Function Create(item As MyModel) As Boolean Implements IRepository(Of MyModel).Create
Context.MyModel.Add(item)
Return Context.SaveChanges() > 0
End Function
Public Function Delete(id As Integer) As Boolean Implements IRepository(Of MyModel).Delete
Context.MyModel.Remove([Get](id))
Return Context.SaveChanges() > 0
End Function
Public Function [Get](id As Integer) As MyModel Implements IRepository(Of MyModel).Get
Return Context.MyModel.Find(id)
End Function
Public Function List() As IQueryable(Of MyModel) Implements IRepository(Of MyModel).List
Return Context.MyModel
End Function
End Class
My service class includes the following reference to the repository...
<Dependency>
Public Property Repository() As IRepository(Of MyModel)
The rest of the service class at the moment is pretty much just a wrapper for the repository methods, but will eventually have more high-level functionality.
In my controller I reference my service like so...
<Dependency>
Public Property MyModelService() As IMyService
Anyway this all seems to work fine, I can add additional bits to the queries at repository, service, or controller level and it always seems to have the correct context. However I'm not sure how it will know to track and close the DBContext, as it's not explicitly registered with Unity.
Does it just figure this out itself because of the <Dependency>
property decoration?
yes, unity is able to resolve the context implicitly. However, when you register it explicitly you'll have more control over the lifetime, because you can tell Unity which lifetimemanager to use. As implicit resolved types are created with the transient lifetimemanager (see also: Unity: Change default lifetime manager for implicit registrations and/or disable them ) the lifetime of your context is the same as the lifetime of your repository.
for reference: https://msdn.microsoft.com/en-us/library/ff660872%28v=pandp.20%29.aspx