Autofac中的AsSelf()作用
關于Autofac中的AsSelf()具體有什么用,有點好奇查了文檔了解了下
Services vs. Components
When you register?components, you have to tell Autofac which?services?that component exposes. By default, most registrations will just expose themselves as the type registered:
// This exposes the service "CallLogger" builder.RegisterType<CallLogger>();Components can only be?resolved?by the services they expose. In this simple example it means:
// This will work because the component // exposes the type by default: scope.Resolve<CallLogger>();// This will NOT work because we didn't // tell the registration to also expose // the ILogger interface on CallLogger: scope.Resolve<ILogger>();You can expose a component with any number of services you like:
builder.RegisterType<CallLogger>().As<ILogger>().As<ICallInterceptor>();Once you expose a service, you can resolve the component based on that service. Note, however, that once you expose a component as a specific service, the default service (the component type) is overridden:
// These will both work because we exposed // the appropriate services in the registration: scope.Resolve<ILogger>(); scope.Resolve<ICallInterceptor>();// This WON'T WORK anymore because we specified // service overrides on the component: scope.Resolve<CallLogger>();If you want to expose a component as a set of services as well as using the default service, use the?AsSelf?method:
builder.RegisterType<CallLogger>().AsSelf().As<ILogger>().As<ICallInterceptor>();Now all of these will work:
// These will all work because we exposed // the appropriate services in the registration: scope.Resolve<ILogger>(); scope.Resolve<ICallInterceptor>(); scope.Resolve<CallLogger>();一個是一個接口有多個實現,AsSelf()的話就是設置為默認的實現了。
參考文檔說明?
總結
以上是生活随笔為你收集整理的Autofac中的AsSelf()作用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Android】Nexus 5X 环境
- 下一篇: Autofac 快速入门