-
Notifications
You must be signed in to change notification settings - Fork 151
Description
Since its inception, the Simple Injector Container class implements System.IServiceProvider. IServiceProvider "defines a mechanism for retrieving a service object; that is, an object that provides custom support to other objects." It contains one GetService(Type) object.
In recent years, however, the IServiceProvider has been hijacked and repurposed making implementing the interface less suited for Simple Injector, because:
- Microsoft added extension methods on top of
IServiceProviderthat don't work on top of Simple Injector, such asCreateScope(). When called on theContainer, it will throw a (confusing) exception. - Microsoft uses it in Web Forms 4.7.2 in a way that breaks the
IServiceProvdercontact. Where theGetServicecontract state thatnullshould be returned "if there is no service object of type serviceType," Web Forms will throw a very nastyNullReferenceExceptionfrom deep down its call stack whenever you dare to returnnull.
To prevent confusion, the IServiceProvider interface should be removed from the Container (and Scope as well). When there's an API that requires the use of IServiceProvider a simple adapter can be created around the Container such that the old behavior is resurrected:
public class ServiceProviderAdapter : IServiceProvider
{
public Container Container {get;set;}
public object GetService(Type type) => this.Container.GetInstanceOrNull(type);
}One question remaines: there is still a need for a method with the behavior of GetService. How should that method be called? GetService, GetInstanceOrNull, GetInstanceOrDefault, TryGetInstance?