AsSelf在autofac中做什么? [英] What does AsSelf do in autofac?

查看:910
本文介绍了AsSelf在autofac中做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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>()允许您注入FooService,但是即使FooService实现了它,也不能注入IFooService.这等效于builder.RegisterType<FooService>().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<FooService>().As<IFooService>()允许您注入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<FooService>().As<IFooService>().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<SomeType>().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中做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆