I'm migrating .NET framework projects into .NET 6. We are using Autofac for DI in .NET Framework projects and looking forward to move MS.DI. In the existing project there is a way to pass constructor params while resolving the object in run time, I m looking for a way to do the same in MS DI.
Example:
public interface IMemberProvider
{
long MemberId { get; }
}
public class FixedMemberProvider : IMemberProvider
{
public MemberProvider(long memberId)
{
MemberId = memberId;
}
public long MemberId { get; set; }
}
I have registered like this,
builder.RegisterType<FixedMemberProvider>().As<IMemberProvider>()
.InstancePerLifetimeScope();
In Middleware or in anyplace I resolve like this,
using var messageScope = _lifetimeScope.BeginLifetimeScope();
if (!string.IsNullOrEmpty(message.MemberId))
messageScope.Resolve<IMemberProvider>(
new TypedParameter(typeof(string), message.MemberId));
So within the scope I can access GetMemberId()
method. Can anyone help to get this done by Microsoft DI.
CodePudding user response:
Basic Microsoft.Extensions.DependencyInjection does not support parameters during resolution. That container is intended to be a lowest-common-denominator conforming container that could be backed by any DI container, from Autofac to Simple Injector. If you want to use additional features, that's specifically why you can back it with a richer container. If you need Autofac features...