27

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!

John Mills
  • 10,020
  • 12
  • 74
  • 121
spspli
  • 3,128
  • 11
  • 48
  • 75

1 Answers1

61

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

Community
  • 1
  • 1
tdragon
  • 3,209
  • 1
  • 16
  • 17
  • Is not specifying either the same as specifying `AsSelf()`? I had the same question about what the purpose of AsSelf was for, but I understood what you said here already... I just am curious if it's redundant? – BVernon Jul 01 '20 at 04:21
  • 2
    Never mind, I see now that if you are not registering a type as any services then there is no need to call `AsSelf()`. It's only when registering it as other services that you may want to call it. – BVernon Jul 01 '20 at 04:25