Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove IServiceProvider from the Container #874

dotnetjunkie opened this issue Dec 9, 2020 · 0 comments

Remove IServiceProvider from the Container #874

dotnetjunkie opened this issue Dec 9, 2020 · 0 comments


Copy link

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
None yet

No branches or pull requests

1 participant