关于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()的话就是设置为默认的实现了。