0

I am trying to automatically defines generic in generic restriction, but I am unable to do it.
Here is my code and want I can do and what I want to do:

public class DummyEntity : IDbId { public int Id { get; set; } }

public class BaseServices<TEntity> { }

public class SomeServices : BaseServices<DummyEntity>{ }


public class BaseController<TService, TEntity> : Controller where TService : BaseServices<TEntity> { }

//I can do this.
public class SomeController : BaseController<SomeServices, DummyEntity> { }

//but I want this.
public class Some2Controller : BaseController<SomeServices> { }  

Is this possible? I do not want to pass also DummyEntity to BaseController, since DummyEntity can be extracted from SomeServices<DummyEntity>.

Creating non-generic BaseService is not an option.

I tried this but it does not compile:

public class Base2Controller<TServices> : Controller where TServices : BaseServices<> { }

I think this question is very similar (if not the same) to this one, but I am hoping this is not the case or if it is, some new C# feature was introduce in last 8 years.

Makla
  • 9,899
  • 16
  • 72
  • 142
  • 1
    I don't believe this is possible to do. – Evan Trimboli Dec 30 '17 at 10:26
  • 3
    *Is this possible? I do not want to pass also `DummyEntity` to `BaseController`, since `DummyEntity` can be extracted from `SomeServices`*. Why? To avoid 13 keystrokes in class definition? And no, its not possible. – InBetween Dec 30 '17 at 10:28
  • 1
    I can feel your pain. No, the inference of generic type parameters from other generic type parameters' own constraints is not supported in C#. – Ondrej Tucny Dec 30 '17 at 10:32
  • @InBetween It's 13 keystrokes until there's a second generic type parameter, a third one… once I ended up with 11 of them. – Ondrej Tucny Dec 30 '17 at 10:33
  • 1
    I’ve closed the question as a duplicate of the linked question because nothing has changed in this regard in C#. And it’s unlikely to change very soon since `BaseService<>` is not actually a real type on its own, so having a type constraint of it would have to work very differently. – poke Dec 30 '17 at 10:33
  • I was really hoping something has changed, since (for example) this is possible: `serviceCollection.AddScoped(typeof(ITableServices<,>), typeof(TableServices<,>));` – Makla Dec 30 '17 at 10:34
  • @OndrejTucny If you have 11 generic type parameters you have bigger issues to solve. – InBetween Dec 30 '17 at 10:40
  • @InBetween Unless you know my code you don't know anything about my 'issues' ;) – Ondrej Tucny Dec 30 '17 at 10:41

0 Answers0