有没有办法使用 .NET Core 上的内置 DI 实现相同的功能?
不,但是您可以在 Autofac's property injection mechanism 的帮助下创建自己的 [inject] 属性。
首先创建你自己的InjectAttribute:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class InjectAttribute : Attribute
{
public InjectAttribute() : base() { }
}
然后创建您自己的InjectPropertySelector,它使用反射来检查标有[inject] 的属性:
public class InjectPropertySelector : DefaultPropertySelector
{
public InjectPropertySelector(bool preserveSetValues) : base(preserveSetValues)
{ }
public override bool InjectProperty(PropertyInfo propertyInfo, object instance)
{
var attr = propertyInfo.GetCustomAttribute<InjectAttribute>(inherit: true);
return attr != null && propertyInfo.CanWrite
&& (!PreserveSetValues
|| (propertyInfo.CanRead && propertyInfo.GetValue(instance, null) == null));
}
}
然后在您的ConfigureServices where you wire up 您的AutofacServiceProvider 中使用您的选择器:
public class Startup
{
public IServiceProvider ConfigureServices(IServiceCollection services)
{
var builder = new ContainerBuilder();
builder.Populate(services);
// use your property selector to discover the properties marked with [inject]
builder.RegisterType<MyServiceX>().PropertiesAutowired((new InjectablePropertySelector(true)););
this.ApplicationContainer = builder.Build();
return new AutofacServiceProvider(this.ApplicationContainer);
}
}
终于在您的服务中,您现在可以使用[inject]:
public class MyServiceX
{
[Inject]
public IOrderRepository OrderRepository { get; set; }
[Inject]
public ICustomerRepository CustomerRepository { get; set; }
}
您当然可以更进一步地采用此解决方案,例如通过在服务的类定义之上使用属性来指定服务的生命周期...
[Injectable(LifetimeScope.SingleInstance)]
public class IOrderRepository
...然后在通过 Autofac 配置服务时检查此属性。但这将超出此答案的范围。