What does AsSelf do in autofac? [duplicate]

Asked at 2017-01-09 06:21:57Z
  • 5 Subscribers

This question already has an answer here:

What is AsSelf() in auto fac? I am new to autofac, what exactly is AsSelf and what are the difference between the two below?

builder.RegisterType().AsSelf().As(); builder.RegisterType().As();

Thank you!

1 answers in total

tdragon Posted at 2017-01-09 07:52:23Z

Typically you would want to inject interfaces, rather than implenetations 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 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 a 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

Answer this questsion