Constraining TService to TRegisterAs on AddNew

Jan 2, 2010 at 9:03 AM

After debugging an exception which was pretty far off (during service dependency injection) from where the problem was introduced (adding a service as an interface which it didn't implement), I wondered why the AddNew method of ServiceCollection which allows registration of a type and an interface doesn't constrain the service to the interface in the type constraints, like so:

        public TService AddNew<TService, TRegisterAs>()
            where TRegisterAs : class
            where TService : TRegisterAs
            return (TService)AddNew(typeof(TService), typeof(TRegisterAs));

I've changed my sources to catch this error at compile time, and wonder if it would make a good patch. If not, what are the scenarios which it would prevent? 

Jan 2, 2010 at 3:55 PM

An excellent idea.  I'll add it to the code base with my next check in (next week).