简体   繁体   中英

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;
   }

   ...
}

Later 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.

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