3

I am using simple injector for my web api project. I have a service which requires a session token in order for it to instantiate.

public class CustomerService
{
   public CustomerService(Auth auth, IRepositoryFactory repositoryFactory)
   {
        // make post call to another web api for validation
        SomeWebApiCallToValidateAuth.vaildate(auth);
   }
}

So for this service, it requires an auth token and a repositoryFactory. I want it to be able to inject the auth parameter (which comes from the http web request) and at the same time to resolve the repository factory with the specified implemented thats registered to the container.

But I am not sure how to register this with simple injector or if there is a way around it. Any help would be great. Thanks.

iyuu
  • 85
  • 1
  • 4
  • Why not have a factory for this service as well? Inject the Repository Factory in there, and call a method with the runtime data. The other option would be to inspect your separation of concerns. There's not enough info in the question for that, so I can't point you in that direction. – krillgar Aug 23 '17 at 22:37
  • You should have a method in the service which takes the token as parameter does the validation. With the current approach the object initialization will fail if the validation fails and that will break the entire control flow. If you still want to go ahead with this approach it will be very tricky coz you need to put the token to some place so that DI container read that token to initialize the service. Not sure which DI container has that support – Chetan Aug 23 '17 at 22:39

1 Answers1

6

Your current approach has several downsides:

Concerning the factory: Inject an IRepository rather than an IRepositoryFactory. This might require you to hide the real repository behind a proxy, as explained here.

Concerning the Auth value, it depends on the need, but if the Auth value is an important part of the API of CustomerService, this justifies adding Auth as argument on the methods of CustomerService. If it is an implementation detail, inject an IAuthProvider abstraction of some sort that allows you to retrieve the value at runtime (after the object graph is built). Again, this all is described in this article.

Steven
  • 166,672
  • 24
  • 332
  • 435