What does AsSelf do in autofac? [duplicate]

谁说我不能喝 提交于 2019-12-12 07:41:16

问题


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>();

Thank you!


回答1:


Typically you would want to inject interfaces, rather than implementations into your classes.

But let's assume you have:

interface IFooService { }

class FooService { }

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().

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.

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().

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.

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).

This is also described in here in Autofac documentation



来源:https://stackoverflow.com/questions/41542079/what-does-asself-do-in-autofac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!