AsSelf 在 autofac 中做了什么?
What does AsSelf do in autofac?
autofac 中的 AsSelf()
是什么?
我是 autofac 的新手,AsSelf
到底是什么,下面两个有什么区别?
builder.RegisterType<SomeType>().AsSelf().As<IService>();
builder.RegisterType<SomeType>().As<IService>();
谢谢!
通常您会希望将接口而不是实现注入到您的 类。
但我们假设您有:
interface IFooService { }
class FooService { }
注册builder.RegisterType<FooService>()
允许你注入FooService
,但你不能注入IFooService
,即使FooService
实现了它。这相当于 builder.RegisterType<FooService>().AsSelf()
.
注册 builder.RegisterType<FooService>().As<IFooService>()
允许您注入 IFooService
,但不能再注入 FooService
- 使用上面显示的 .As<T>
"overrides" 默认注册 "by type" .
要能够通过类型和接口注入服务,您应该将 .AsSelf()
添加到之前的注册中:builder.RegisterType<FooService>().As<IFooService>().AsSelf()
.
如果您的服务实现了很多接口并且您想要将它们全部注册,您可以使用 builder.RegisterType<SomeType>().AsImplementedInterfaces()
- 这允许您通过它实现的任何接口来解析您的服务。
您必须明确注册,因为 Autofac 不会自动注册(因为在某些情况下您可能不想注册某些接口)。
中也有描述
autofac 中的 AsSelf()
是什么?
我是 autofac 的新手,AsSelf
到底是什么,下面两个有什么区别?
builder.RegisterType<SomeType>().AsSelf().As<IService>();
builder.RegisterType<SomeType>().As<IService>();
谢谢!
通常您会希望将接口而不是实现注入到您的 类。
但我们假设您有:
interface IFooService { }
class FooService { }
注册builder.RegisterType<FooService>()
允许你注入FooService
,但你不能注入IFooService
,即使FooService
实现了它。这相当于 builder.RegisterType<FooService>().AsSelf()
.
注册 builder.RegisterType<FooService>().As<IFooService>()
允许您注入 IFooService
,但不能再注入 FooService
- 使用上面显示的 .As<T>
"overrides" 默认注册 "by type" .
要能够通过类型和接口注入服务,您应该将 .AsSelf()
添加到之前的注册中:builder.RegisterType<FooService>().As<IFooService>().AsSelf()
.
如果您的服务实现了很多接口并且您想要将它们全部注册,您可以使用 builder.RegisterType<SomeType>().AsImplementedInterfaces()
- 这允许您通过它实现的任何接口来解析您的服务。
您必须明确注册,因为 Autofac 不会自动注册(因为在某些情况下您可能不想注册某些接口)。
中也有描述