What does AsSelf do in autofac? [duplicate]

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

Leave a Comment

tech