Autofac difference between case and case

I started using Autofac following these tutorials: http://flexamusements.blogspot.com/2010/09/dependency-injection-part-3-making-our.html

A simple class without a parameter in the constructor

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

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

Simple class with one parameter in the constructor

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

I don’t understand why we use a lambda expression to register this class (and what this expression does for sure) and why we cannot enter this code

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

Thank you in advance for your help.

+6
source share
3 answers

You cannot write this code because it does not make sense in C #.
RegisterType - a general method; general methods should accept types as general parameters.

You are trying to register a type with a custom way to create it (inyour case, constructor parameter); the only way C # to indicate such a thing is with a lambda expression (or another delegate).

+9
source

The lambda variant allows us to do some logic when building an instance.

+2
source

Btw is the best solution for this. Autofac introduced the .WithParameter() extension into its registration constructor.

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

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

+2
source

Source: https://habr.com/ru/post/900631/


All Articles