Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofac difference between Register and RegisterType

Tags:

autofac

I have started to use Autofac following this tutorials: http://flexamusements.blogspot.com/2010/09/dependency-injection-part-3-making-our.html

Simple class with no parameter in the constructor

builder.RegisterType<ConsoleOutputService>().As<IOutputService>();

As explained in the tutorial, the code above can be read as: setup ConsoleOutputService as the implementation of IOutputService

Simple class with one parameter in the constructor

builder.Register(c => new MultipleOutputService(outputFilePath)).As<IOutputService>();

I don't understand why are we using a lambda expression to register this class (and what does this expression exactly does) and why we can't type this code

builder.RegisterType<MultipleOutputService(outputFilePath)>().As<IOutputService>();

Thanks in advance for your help

like image 998
JuChom Avatar asked Nov 02 '11 17:11

JuChom


2 Answers

Btw there is a better solution to this Autofac introduced the .WithParameter() extension to their registration builder.

.RegisterType<MultipleOutputService>().As<IOutputService>().WithParameter("parameterName", "parameterValue");

This should cater for the event that you need to pass something other than an interface type to one of your constructors

like image 136
Hano Johannes Rossouw Avatar answered Nov 07 '22 10:11

Hano Johannes Rossouw


You can't write that code because it doesn't make sense in C#.
RegisterType is a generic method; generic methods must take types as generic parameters.

You're trying to register a type with a custom way to create it (inyour case, a constructor parameter); the only way that C# supports to specify such a thing is a lambda expression (or other delegate).

like image 28
SLaks Avatar answered Nov 07 '22 10:11

SLaks