我在大会中有以下课程
AutofacDotMemory
public interface IOutput:IDisposable
{
void Write(string content);
}
public class ConsoleOutput : IOutput
{
public void Write(string content)
{
Console.WriteLine(content);
}
public void Dispose()
{
// TODO release managed resources here
}
}
public interface IDateWriter:IDisposable
{
void WriteDate();
}
public class TodayWriter : IDateWriter
{
private IOutput _output;
public TodayWriter( IOutput output)
{
this._output = output;
}
public void WriteDate()
{
this._output.Write(DateTime.Today.ToShortDateString());
}
public void Dispose()
{
// TODO release managed resources here
}
}
在我的另一个测试程序集中,我还引用了 Autofac,并尝试在程序集扫描级别使用ExternallyOwned,并使用以下测试代码:
[Test]
public void ExternallyOwnedTest()
{
var builder = new ContainerBuilder();
builder.RegisterAssemblyTypes(typeof(IDateWriter).Assembly)
.ExternallyOwned();
builder.RegisterType<ConsoleOutput>().As<IOutput>();
builder.RegisterType<TodayWriter>().As<IDateWriter>();
var container = builder.Build();
var registration = container.ComponentRegistry.TryGetRegistration(new TypedService(typeof(IDateWriter)), out var foundRegistration);
TestContext.WriteLine(registration);
var isExternallyOwned = registration && foundRegistration.Ownership == InstanceOwnership.ExternallyOwned;
Assert.IsTrue(isExternallyOwned, $"{nameof(TodayWriter)} is not externally owned");
container.Dispose();
}
测试失败,因为
TodayWriter
不是外部拥有的。
但是如果我将注册代码更改为以下内容,以便根据注册类型完成:
var builder = new ContainerBuilder();
builder.RegisterType<ConsoleOutput>().As<IOutput>();
builder.RegisterType<TodayWriter>().As<IDateWriter>().ExternallyOwned(); //now this works
var container = builder.Build();
var registration = container.ComponentRegistry.TryGetRegistration(new TypedService(typeof(IDateWriter)), out var foundRegistration);
TestContext.WriteLine(registration);
var isExternallyOwned = registration && foundRegistration.Ownership == InstanceOwnership.ExternallyOwned;
Assert.IsTrue(isExternallyOwned, $"{nameof(TodayWriter)} is not externally owned");
container.Dispose();
现在这个测试通过了,因为
TodayWriter
是外部拥有的。
如何确保给定程序集中的所有类型(或至少大多数类型,受到
Where
过滤条件)注册为外部拥有?我不想遍历所有注册类型并在其中添加一个ExternallyOwned 关键字。
在你的测试中...
builder.RegisterAssemblyTypes(typeof(IDateWriter).Assembly)
.ExternallyOwned();
builder.RegisterType<ConsoleOutput>().As<IOutput>();
builder.RegisterType<TodayWriter>().As<IDateWriter>();
您已注册
TodayWriter
两次。一旦通过装配扫描,一次手动。
在装配扫描中,它被注册为
ExternallyOwned
。但后来你覆盖了并将其注册为正常,这是不是ExternallyOwned
。报名中,最后一名获胜。