简体   繁体   English

Autofac的DefaultConventions

[英]DefaultConventions with Autofac

I am not sure if I am missing something here but can't find the answer anywhere. 我不确定我是否在这里遗漏了一些东西,但是找不到任何答案。 In structuremap I can do the following: 在structuremap中,我可以执行以下操作:

                x.Scan(scan =>
                {
                    scan.TheCallingAssembly();
                    scan.WithDefaultConventions();
                });

This effectively means: "if while scanning I find an interface ISampleClass, and there is a type SampleClass that implements ISampleClass, then register SampleClass as the default type for ISampleClass". 这实际上意味着:“如果在扫描时我找到一个接口ISampleClass,并且有一个实现ISampleClass的SampleClass类型,则将SampleClass注册为ISampleClass的默认类型”。

How do I do this with Autofac? 如何使用Autofac做到这一点?

Autofac seems to provide this: Autofac似乎提供了以下功能:

 builder.RegisterAssemblyTypes(assemblies)
        .AsImplementedInterfaces();

which registers all interfaces it finds to whatever concrete types it finds. 它会将找到的所有接口注册为找到的任何具体类型。 Is there a way to get to intelligently register based on the name of the class and the interface like structuremap does? 有没有一种方法可以基于类的名称和类似于structuremap的接口进行智能注册?

This seems like a basic ask of any DI framework. 这似乎是任何DI框架的基本要求。

The Where method should fit your needs. Where方法应适合您的需求。

builder.RegisterAssemblyTypes(assemblies)
       .Where(t => t.Name.EndsWith("XXX"))
       .AsImplementedInterfaces();

By the way, you can also use the As method that will act as a filter in this case. 顺便说一句,在这种情况下,您也可以使用As方法作为过滤器。

builder.RegisterAssemblyTypes(assemblies)
       .As<IFoo>();

Only types that implement IFoo will be registered. 仅实现IFoo类型将被注册。

You can find further information on assembly scanning on the documentation page 您可以在文档页面上找到有关装配扫描的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM