Created
June 7, 2019 18:52
-
-
Save chivandikwa/4449ce750205476ae3d6e8ccc3c70ef7 to your computer and use it in GitHub Desktop.
Simple injector does not resolve types that have unregistered dependencies even when they are optional
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using Microsoft.Extensions.DependencyInjection; | |
using SimpleInjector; | |
namespace SimpleInjectorNullableConstructor | |
{ | |
internal interface ISample | |
{ | |
} | |
internal class Sample : ISample | |
{ | |
public Sample(Dictionary<string, string> junk = null) | |
{ | |
} | |
} | |
class Program | |
{ | |
//Simple injector does not resolve types that have unregistered dependencies even when they are optional | |
static void Main(string[] args) | |
{ | |
//The Microsoft.Extensions.DependencyInjection implementation can handle this case | |
IServiceCollection serviceCollection = new ServiceCollection(); | |
serviceCollection.AddTransient<ISample, Sample>(); | |
ServiceProvider service = serviceCollection.BuildServiceProvider(); | |
var sample =service.GetService<ISample>(); | |
//SimpleInjector fails on verify because of the unregistered Dictionary<string, string> | |
var container = new Container(); | |
container.Register<ISample, Sample>(); | |
container.Verify(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Turns out this is an explicit decisions based on question I opened here: simpleinjector/SimpleInjector#724 (comment)
Response:
This is a very explicit design decision. A constructor declares a component's required dependencies. It therefore doesn't make sense to make a required dependency optional. Instead of making dependencies optional, a better solution is to apply the Null Object pattern.