<分区>
autofac 中的 AsSelf()
是什么?
我是 autofac 的新手,AsSelf
到底是什么,下面两者之间有什么区别?
builder.RegisterType<SomeType>().AsSelf().As<IService>();
builder.RegisterType<SomeType>().As<IService>();
谢谢!
<分区>
autofac 中的 AsSelf()
是什么?
我是 autofac 的新手,AsSelf
到底是什么,下面两者之间有什么区别?
builder.RegisterType<SomeType>().AsSelf().As<IService>();
builder.RegisterType<SomeType>().As<IService>();
谢谢!
最佳答案
通常您会希望将接口(interface)而不是实现注入(inject)到您的类中。
但让我们假设您有:
interface IFooService { }
class FooService { }
注册 builder.RegisterType<FooService>()
允许你注入(inject) FooService
, 但你不能注入(inject) IFooService
, 即使FooService
实现它。这相当于 builder.RegisterType<FooService>().AsSelf()
.
注册 builder.RegisterType<FooService>().As<IFooService>()
允许你注入(inject) IFooService
, 但不是 FooService
不再 - 使用 .As<T>
上面显示的“按类型”“覆盖”默认注册。
要能够同时通过类型和接口(interface)注入(inject)服务,您应该添加 .AsSelf()
之前的注册:builder.RegisterType<FooService>().As<IFooService>().AsSelf()
.
如果你的服务实现了很多接口(interface),你想把它们全部注册,你可以使用builder.RegisterType<SomeType>().AsImplementedInterfaces()
- 这允许您通过它实现的任何接口(interface)解析您的服务。
您必须明确注册,因为 Autofac 不会自动注册(因为在某些情况下您可能不想注册某些接口(interface))。
here in Autofac documentation 中也对此进行了描述
关于c# - AsSelf 在 autofac 中做了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41542079/
相关文章:
c# - 是否可以将不同的接口(interface)绑定(bind)到实现所有接口(interface)的类的同一个实例?
asp.net-mvc - 将 Ninject 与 Udi Dahan 的领域事件结合使用
unit-testing - 如何将抽象工厂注入(inject)到实体的方法中?
c# - Moq 和 Equals() 的组合使 MS 测试框架崩溃
java - Spring 能否理解 @Inject 将 Weld 替换为 JSR-299 实现?
python - 如何使用 Python 实现运行时对象(不同)实现
java - 使用 Spring 将包中的所有实例添加到列表中