Skip to main content
 首页 » 编程设计

c#之Autofac 的编译时支持

2024年02月20日14Free-Thinker

我们为我们的项目调查 DI 容器。现在我们在 Autofac 和 CaSTLe Windsor 之间做出选择。有一点对我们来说非常重要:Autofac 的强类型注册。

例子:

public interface ITestAutofac 
{         
} 
 
public class NotDerivedFrom 
{         
} 

对于温莎我可以这样写-

var cont = new WindsorContainer(); 
 
cont.Register(Component 
    .For<ITestAutofac>().ImplementedBy<NotDerivedFrom>()); 

并且它会在编译时失败。 Resharper 可以很容易地帮助解决这个问题。

对于 Autofac 我可以这样写 -

builder.Register(c => new NotDerivedFrom()).As<ITestAutofac>(); 
 
var form = container.Resolve<ICustomForm>(); 

它会在运行时失败。

如何通过编译时检查在 Autofac 中注册类型?

请您参考如下方法:

builder.Register<NotDerivedFrom>().As<ITestAutofac>() 

对于 Autofac,这会在运行时失败,但当您调用 builder.Build() 时会发生这种情况,考虑到这一点,这并不是很糟糕。我同意,它不如编译时支持好,但您可以找到调用 builder.Build() 的单元测试。不要忘记大多数 DI 配置错误无论如何都不会被编译器捕获,你需要你的容器,a verifiable configuration ,以及一些单元测试以查找所有配置错误。

How can I register types in Autofac with compile time checking?

如果你愿意,你可以写一个简单的扩展方法来添加编译时检查:

public static void Register<TService, TImplementation>( 
    this ContainerBuilder builder) 
    // Note the generic type constraints here 
    where TImplementation: class, TService 
    where TService: class 
{ 
    builder.Register<TImplementation>().As<TService>(); 
} 

这使您可以按如下方式进行原始注册:

build.Register<ITestAutofac, NotDerivedFrom>(); 

这将在编译时失败。