gpt4 book ai didi

c# - Autofac 中的装饰器和属性注入(inject)

转载 作者:行者123 更新时间:2023-12-03 02:26:54 52 4
gpt4 key购买 nike

我正在尝试为这些使用属性注入(inject)的服务注册装饰器。
当我添加containerBuilder.RegisterDecorator<ServiceDecorator, IService>()时该属性不再被注入(inject)。
我猜 Autofac 正在尝试将其注入(inject)装饰器而不是原始服务。

我编写了一些测试来展示这个问题。有服务和装饰器:

public interface IService
{
bool NestedServiceIsNotNull();
}

public interface INestedService { }

public class Service : IService
{
public INestedService NestedService { get; set; }

public bool NestedServiceIsNotNull()
{
return NestedService != null;
}
}

public class NestedService : INestedService { }

public class ServiceDecorator : IService
{
private readonly IService _original;

public ServiceDecorator(IService original)
{
_original = original;
}

public bool NestedServiceIsNotNull()
{
return _original.NestedServiceIsNotNull();
}
}

测试方法:

[TestMethod]
public void PropertyInjectedServiceShouldNotBeNull()
{
var builder = new ContainerBuilder();
builder.RegisterType<NestedService>().As<INestedService>();
builder.RegisterType<Service>().As<IService>().PropertiesAutowired();
var container = builder.Build();
var service = container.Resolve<IService>();

Assert.IsTrue(service.NestedServiceIsNotNull());
}

[TestMethod]
public void PropertyInjectedServiceShouldNotBeNullEvenIfDecoratorRegistered()
{
var builder = new ContainerBuilder();
builder.RegisterType<NestedService>().As<INestedService>();
builder.RegisterType<Service>().As<IService>().PropertiesAutowired();
// Here's the difference - decorating the service
// causes the assertion to fail.
builder.RegisterDecorator<ServiceDecorator, IService>();
var container = builder.Build();
var service = container.Resolve<IService>();

Assert.IsTrue(service.NestedServiceIsNotNull());
}

第一个测试通过,但第二个测试因断言而失败。

这是正确的行为吗?
我正在处理一个遗留项目,因此我不应该通过将依赖项移至构造函数来更改现有代码。
有什么办法可以解决这个问题吗?

最佳答案

看起来...您发现了一个错误!哟! I've filed an issue on your behalf here.

但是,一切并没有丢失 - 您仍然可以按照自己想要的方式使用装饰器,只需使用较旧的不太漂亮的 Autofac 装饰器语法即可完成。

var builder = new ContainerBuilder();
builder.RegisterType<NestedService>().As<INestedService>();

// Decorating the service with the old syntax works.
builder.RegisterType<Service>().Named<IService>("service").PropertiesAutowired();
builder.RegisterDecorator<IService>((c, inner) => new ServiceDecorator(inner), fromKey: "service");

var container = builder.Build();
var service = container.Resolve<IService>();

Assert.True(service.NestedServiceIsNotNull());

There is more documentation on how to work with this older syntax here.

关于c# - Autofac 中的装饰器和属性注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58590783/

52 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com