vendredi 29 mai 2015

Injecting an instance using Unity whose constructor parameter is not known

I have an interface as follows

public interface IDataProvider
{
     List<string> GetData();
}

Implementation of it

public class TextDataProvider: IDataProvider
{
    public TexDataProvider(string source){...}
    public List<string> GetData() {...}
}

One of my services uses IDataProvider to get data. Different implementations could be injected by changing the Unity Register method with alternate implementations.

However, the source parameter of the constructor is only known at the time GetData is called. So, when Unity registers an implementation of IDataProvider, the source parameter is not known.

I understand one alternative is to move the source to GetData method and the other is to create an Abstract Factory whose CreateMethod takes the source parameter and passes it to IDataProvider implementation constructor. Then we can inject Factory instead of IDataProvider instances.

But is there a better way this can be addressed ?

Aucun commentaire:

Enregistrer un commentaire