Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does AsSelf do in autofac? [duplicate]

Tags:

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!

like image 499
spspli Avatar asked Jan 09 '17 06:01

spspli


People also ask

What is AsImplementedInterfaces?

AsImplementedInterfaces<TLimit>(IRegistrationBuilder<TLimit, ScanningActivatorData, DynamicRegistrationStyle>) Specifies that a type from a scanned assembly is registered as providing all of its implemented interfaces.

How do I register an Autofac interface?

Register by Type var builder = new ContainerBuilder(); builder. RegisterType<ConsoleLogger>(); builder. RegisterType(typeof(ConfigReader)); When using reflection-based components, Autofac automatically uses the constructor for your class with the most parameters that are able to be obtained from the container.


1 Answers

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

like image 163
tdragon Avatar answered Sep 17 '22 17:09

tdragon