Reputation: 1338
I have a Ninject Module which is basically something along the lines of:
public class ExternalApiService {
public string BaseUriAddress {get; set;}
public string EndpointAddress {get; set;}
}
Then within my various classes I do the following:
[Inject]
public IExternalApiService ExternalApiService {get; set;}
The injection works great, but the problem I have is that when I come around to using the service within my code, I have to manually inject the BaseUriAddress
and the EndpointAddress
. This is a tad annoying, as it means I have to set up some constructors, and manual IOC which kind of nullifies the point of an IOC framework.
I saw that I can do constructor and field injection, however, it seems like all of these are determined at compile time. This isn't quite right, because whenever I use the ExternalApiService
, I am not guaranteed the same Base Address nor Endpoint Address.
Ideally I am looking for some way to specify those arguments at run time, using Ninject, but have had difficulty finding how / if it's possible. Ideally something like this:
[Inject(BaseUriAddress = "", EndpointAddress = "")]
public IExternalApiService ExternalApiService {get; set;}
Obviously not exactly that, but that is essentially the kind of functionality that I am trying to implement. Is this possible?
Upvotes: 0
Views: 391
Reputation: 13233
If it's transient and it requires "dynamic" parameters then you need to use a factory. You can go with an Abstract Factory as Mark Seemann describes it.
Alternatively you can use a Func<TParam1,TParam2,..,TToBeCreated>
or an interface-based factory with dynamically generated implementation (dynamic-proxy based approach) - both of which are provided by Ninject.Extensions.Factory.
I personally prefer the interface based factory for it's very nice to read and unit test, but beware, the disadvantages that Mark Seemann outlines (also in the link above) do apply.
Upvotes: 1