Skip to content

Remove IServiceProvider from the Container #874

@dotnetjunkie

Description

@dotnetjunkie

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 IServiceProvider that don't work on top of Simple Injector, such as CreateScope(). When called on the Container, it will throw a (confusing) exception.
  • Microsoft uses it in Web Forms 4.7.2 in a way that breaks the IServiceProvder contact. Where the GetService contract state that null should be returned "if there is no service object of type serviceType," Web Forms will throw a very nasty NullReferenceException from deep down its call stack whenever you dare to return null.

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?

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions