Sorry, you canβt. This is not how generics are designed to work in C #. If you go with this template, you will always have to eliminate which version of the interface you want to call Get() by pressing repo :
IFooBarRepository repo = SomeMethodThatGetsTheActualClass(); Foo foo = ((IRepository<Foo>)repo).Get(1);
which is probably not the one you want.
You could, of course, implement proxy methods in the implementation of IFooBarRepository that return the correct types ... but again, this may not be what you are looking for.
However, you can create properties on IFooBarRepository that improve the syntax:
interface IFooBarRepository : IRepository<Foo>, IRepository<Bar> { IRepository<Foo> FooGetter { get; } IRepository<Bar> BarGetter { get; } }
Now you can write:
IFooBarRepository repo = SomeMethodThatGetsTheActualClass(); Foo foo = repo.FooGetter.Get(1); Bar bar = repo.BarGetter.Get(2);
In general, it is advisable to avoid common methods that do not accept type parameters of type parameters as formal arguments. In your case, you are trying to code the semantics of the repositories directly into the type system. Perhaps you should separate this responsibility from the type that expresses the behavior of the repository and the separate type that expresses the behavior of the sample objects.
source share