问题描述
autofac 中的 AsSelf()
是什么?我是 autofac 的新手,AsSelf
到底是什么,下面两者有什么区别?
What is AsSelf()
in autofac?I am new to autofac, what exactly is AsSelf
and what are the difference between the two below?
builder.RegisterType<SomeType>().AsSelf().As<IService>();
builder.RegisterType<SomeType>().As<IService>();
谢谢!
推荐答案
通常,您希望将接口而不是实现注入到您的类中.
Typically you would want to inject interfaces, rather than implementations into your classes.
但让我们假设您有:
interface IFooService { }
class FooService { }
注册builder.RegisterType()
可以注入FooService
,但是不能注入IFooService
,即使FooService
实现它.这相当于 builder.RegisterType().AsSelf()
.
Registering builder.RegisterType<FooService>()
allows you to inject FooService
, but you can't inject IFooService
, even if FooService
implements it. This is equivalent to builder.RegisterType<FooService>().AsSelf()
.
注册 builder.RegisterType().As()
允许您注入 IFooService
,但不再注入 FooService
- 使用 .As<T>
覆盖"上面显示的按类型"的默认注册.
Registering builder.RegisterType<FooService>().As<IFooService>()
allows you to inject IFooService
, but not FooService
anymore - using .As<T>
"overrides" default registration "by type" shown above.
为了有可能通过类型和接口注入服务,您应该将 .AsSelf()
添加到之前的注册中:builder.RegisterType().As().AsSelf()
.
To have the possibility to inject service both by type and interface you should add .AsSelf()
to previous registration: builder.RegisterType<FooService>().As<IFooService>().AsSelf()
.
如果您的服务实现了许多接口并且您想将它们全部注册,您可以使用 builder.RegisterType().AsImplementedInterfaces()
- 这允许您通过任何接口解析您的服务它实现了.
If your service implements many interfaces and you want to register them all, you can use builder.RegisterType<SomeType>().AsImplementedInterfaces()
- this allows you to resolve your service by any interface it implements.
您必须明确注册,因为 Autofac 不会自动完成(因为在某些情况下您可能不想注册某些接口).
You have to be explicit in your registration, as Autofac does not do it automatically (because in some cases you might not want to register some interfaces).
这也在 在 Autofac 文档中
这篇关于AsSelf 在 autofac 中做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!