sps*_*pli 18 c# dependency-injection inversion-of-control autofac
什么是自动面板中的AsSelf()?我是autofac的新手,AsSelf究竟是什么,下面两者有什么区别?
.builder.RegisterType()AsSelf()为()..builder.RegisterType()为();
谢谢!
小智 34
通常,您希望将接口而不是实现注入到类中.
但是我们假设你有:
interface IFooService { }
class FooService { }
Run Code Online (Sandbox Code Playgroud)
注册builder.RegisterType<FooService>()允许你注入FooService,但你不能注入IFooService,即使FooService实现它.这相当于builder.RegisterType<FooService>().AsSelf().
注册builder.RegisterType<FooService>().As<IFooService>()允许您注入IFooService,但FooService不再.As<T>注册- 使用上面显示的"覆盖"默认注册"按类型".
为了有可能通过类型和接口注入服务,您应该添加.AsSelf()到以前的注册:builder.RegisterType<FooService>().As<IFooService>().AsSelf().
如果您的服务实现了许多接口并且您想要全部注册它们,您可以使用builder.RegisterType<SomeType>().AsImplementedInterfaces()- 这允许您通过它实现的任何接口来解析您的服务.
您必须明确注册,因为Autofac不会自动执行此操作(因为在某些情况下您可能不想注册某些接口).
这也在Autofac文档中进行了描述