开发者

Create new Repositories while still using Dependency Injection with wcf

I have a wcf service that takes in an IRepository

IRepository irepo;

public SomeService(IRepository repo)
{
    this.irepo = repo;
}

The repositories contain methods like Save, Delete, etc and take in a CustomDataContext through a constructor:

public class ExampleRepository: IRepository, IDisposible {

   public ExampleRepository(CustomDataContext datacontext)
   {
       this.dc = datacontext;
   }

   ...
}

Late开发者_JAVA技巧r on in the service i have a few methods that will need to use a repository (and later dispose of it in the method). Now since i want to use Dependency Injection to switch out repositories for testing and not testing, how do i declare the concrete repository. I could create a new Instance of the repository like so:

using (IRepository repos = (IRepository)Activator.CreateInstance(irepo.GetType(), new object[] {new CustomDataContext()} ))
{
     ...
}

but im assuming this is a slow way of doing it (and incorrect)

Is there a way to do make a new Repository based on the injected type, or am i just making things more complicated then necessary?

Thanks in advance


The whole idea of dependency injection is that there's some container which resolves your dependencies for you. Is there a reason your not using a framework for injecting your dependencies, say structuremap or unity for example?

If you do have a container you should request a new instance of your type from the container which instantiates it for you and resolves all the dependencies if any for you of that specific type.


Try injecting Func<CustomDataContext, IRepository> if your container allows such behavior. Otherwise, inject a IRepositoryFactory which would have a CreateInstance method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜