Dependency injection in .NET and WithParameter
goodie
#66071
-
Hi, I would like to port an app using Autofac DI container to use .NET's dependency container because MAUI is using the latter DI library. One thing that I do not know how to rewrite elegantly1 is: _ = builder.RegisterType<DatabaseMain>().WithParameter(new TypedParameter(typeof(string), appDataFolder)).InstancePerLifetimeScope(); where public class DatabaseMain
{
// ...
public DatabaseMain(string appDataFolder, TypeA typeA, TypeB typeB, TypeC typeC)
{
// ...
}
}
Now I know I can write: Services.AddSingleton((IServiceProvider provider) => new DatabaseMain(
appDataFolder,
provider.GetRequiredService<TypeA>(),
provider.GetRequiredService<TypeB>(),
provider.GetRequiredService<TypeC>()
); but it is more verbose than the Autofac's syntax and when I refactor Obviously, I can create some wrapper type Do you know about another not mentioned solution for this problem? Thanks! Footnotes
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
You can use services.AddSingleton(sp =>
ActivatorUtilities.CreateInstance<DatabaseMain>(sp, appDataFolder)
); There's a few other methods on ActivatorUtilities that can be used to support such scenarios and create factories that are aware of additional parameters. |
Beta Was this translation helpful? Give feedback.
You can use
ActivatorUtilities.CreateInstance
to pass in additional, non-DI parametersThere's a few other methods on ActivatorUtilities that can be used to support such scenarios and create factories that are aware of additional parameters.