lundi 10 décembre 2018

Implement Factory with generic interface

I am abstracting out dependencies from contracts to decouple the dependencies

// Abstraction -- This can be published as contract where implementation needs to implement method. Most importantly 3rd party types are not present/tied to contract

public interface ISourceFactory {
   T GetSource<T>();
}


// Implementation which depends on specific source like 3rd party

public class SourceFactory {
    public T GetSource<T>()   //Unable to make this work
    {
        Type listType = typeof(T);
        if (listType == typeof(SomeBase))
        {
            return _connection.GetSource<T>();
        }
        if(listType == typeof(ExternalBase)){
            return _exconnection.GetSource<T>();
        }
        throw new Exception("Not supported");
    }

    private Connection _connection;
    private ExternalConnection _exconnection;
}

// 3rd party implementation
public class Connection {
    public T GetSource<T> where T : SomeBase
}

// 3rd party implementation
public class ExternalConnection {
    public T GetSource<T> where T : ExternalBase
}

However I am unable to make SourceFactory.GetSource to working as it cribs that T can't be used as generic parameter.

Can anyone suggest what's the generic approach for this problem?

Aucun commentaire:

Enregistrer un commentaire