Purusartha
Purusartha

Reputation: 1010

c# generic interface where parameter is generic

I have an interface

public interface IOfflineBackedRepo<TSummary,TDetail>
{
    Task SyncAsync();
}

this has different concrete implementations. I am trying to develop a service lets developers register different implementations of IOfflineBackedRepo interface and separately call SyncAsync at a later point in time. The new interface should be similar to the below, except this is not a valid syntax.

public interface ISyncManager<T> where T : IOfflineBackedRepo<TSummary, TDetail>
{
    void Register(T repo);

    Task SyncNowAsync(); // this loops through and calls SyncAsync on the repo
}

How to fix the syntax issue?

Upvotes: 2

Views: 77

Answers (1)

Thaina Yu
Thaina Yu

Reputation: 1512

ISyncManager does not have anywhere mentioning TSummary,TDetail in it's scope

TSummary and TDetail is defined and exist only around IOfflineBackedRepo. When you try to use it anywhere else you must define a type you will use in substitute for them. It could be actual type or a type that you would get from generic argument but you must define it somewhere around ISyncManager

At the most basic ways,

public interface ISyncManager<T,U,V> where T : IOfflineBackedRepo<U,V>
{
    void Register(T repo);

    Task SyncNowAsync(); // this loops through and calls SyncAsync on the repo
}

For the ease of use I think you should just separate interface

public interface IOfflineBackedRepo
{
    Task SyncAsync(); // this function is not typed specific right?
}

public interface IOfflineBackedRepo<TSummary,TDetail> : IOfflineBackedRepo
{
    // other definition about type specific
}

public interface ISyncManager<T> where T : IOfflineBackedRepo
{
    void Register(T repo);

    Task SyncNowAsync(); // this loops through and calls SyncAsync on the repo
}

And I guess ISyncManager is actually just a collection. I think it would be better if you could just make extension method for collection

public static class SyncManagerExt
{
    // Register is just Add to collection
    public static Task SyncNowAsync(this ICollection<T> items) where T : IOfflineBackedRepo
    {
        // loops through items and calls SyncAsync on the repo
    }
}

Upvotes: 1

Related Questions