简体   繁体   中英

Dependency injection for repository pattern in WCF service using Entity Framework

I have WCF service that takes in IRepository.

IRepository repository;

public MyWcfService(IRepository repository)
{
    this.repository= repository;
}

The repository is need to be based on Entity Framework. It has methods Get , Save , etc...

My question is how should I implement this repository class, if I want to create and dispose DbContext every time when I called method from this WCF service class.

PS I'm using Ninject library for resolving dependencies

If you want to take your database context as a dependency to your repository class then your repository class should implement IDisposable and in Dispose method you should be disposing the database context.

Your repository should be disposed at the end of http request processing therefor you should register IRepository using InRequestScope(). You should also register your WCF Service using InRequestScope() so it does not outlive the IRepository.

Here's documentation on InRequestScope() :
https://github.com/ninject/Ninject.Web.Common/wiki/InRequestScope

and difference between object scopes in ninject:
https://github.com/ninject/ninject/wiki/Object-Scopes

Using dependency injection in WCF is a bit different. You need to hook into the Instance creation pipeline, and service host.

There's a specific Ninject extension to make this easier: Ninject.extensions.Wcf

https://github.com/ninject/Ninject.Extensions.Wcf

There's also this blog that will explain how to use it:

http://blog.tonysneed.com/2011/10/24/using-ninject-with-wcf-services/

Note: this is a bit involved, so sorry for the link-only references... someone else is free to create a full answer based on this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM