Reputation: 45
I am using this in Autofac with the following registration:
builder.RegisterType<SBOTaskerHelper>()
.As<ISBOTaskerHelper>()
.AsSelf()
.UsingConstructor(
typeof(IPrincipal),
typeof(IPortalSettings),
typeof(ILogger<SBOTaskerHelper>),
typeof(bool))
.WithParameter("debugMode", Portal.Site.DebugMode)
.InstancePerRequest();
Moving to ASP.NET Core dependency injection. How to pass constructors and parameters to configure services DI?
Upvotes: 2
Views: 959
Reputation: 172646
The following registration would be roughly the same:
services.AddScoped<SBOTaskerHelper>(
p => ActivatorUtilities.CreateInstance<SBOTaskerHelper>(
p, Portal.Site.DebugMode));
services.AddScoped<ISBOTaskerHelper>(
p => p.GetRequiredService<SBOTaskerHelper>());
ActivatorUtilities.CreateInstance
is a helper method of MS.DI. It allows creating the given type, where its dependencies are resolved from the supplied IServiceProvider
, while allowing constructor arguments to be overridden. In this case we're instructing MS.DI to supply the Portal.Site.DebugMode
to the first bool
property in SBOTaskerHelper
's constructor.
Note that there is no .As<T>().AsSelf()
in MS.DI. You need to add a second registration and forward the registration to the previous one. This is done using services.AddXXX<IX>(p => p.GetRequiredService<X>())
.
Upvotes: 2