Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save chivandikwa/4449ce750205476ae3d6e8ccc3c70ef7 to your computer and use it in GitHub Desktop.
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
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();
}
}
}
@chivandikwa
Copy link
Author

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.

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