IntroductionAutowiring is the process of creating components by selecting a constructor according to the services available in the container. This is done via reflection, so that in effect the container adapts its component creation behaviour to the configured environment. Choosing ConstructorsAutofac automatically chooses the constructor with the most parameters that are able to be obtained from the container. To select a different constructor, specify it when the component is registered: builder.Register(typeof(MyFoo)).UsingConstructor(typeof(int)); This example will use the MyFoo(int) constructor regardless of the other constructors that are available. Additional Constructor ArgumentsThere are two ways that additional constructor arguments can be provided - at registration time and at resolve time. Both will be used when autowiring instances. At RegistrationUse the WithArguments() methods to associate parameters with a component that will be used every time the component is created: builder.Register<MyFoo>()
.WithArguments(
new NamedParameter("message", "Hello!"),
new NamedParameter("meaning", 42));At ResolveYou can pass Parameter instances to all of the Resolve() overloads. PrecedenceParameters provided at Resolve() time will override any other parameter with the same name. Parameters provided at registration will override any possible service matches that exist in the container. Making Autowiring Work for YouBy far the greatest use for Autowiring is cutting down on repetitive configuration. Wherever there are many similar components to register, Autowiring can be used: var builder = new ContainerBuilder();
var controllerTypes =
from type in Assembly.Load("MyWebApp").GetTypes()
where typeof(IController).IsAssignableFrom(type)
select type;
foreach (var controllerType in controllerTypes)
builder.Register(controllerType).FactoryScoped();This doesn't preclude you from subsequently overriding one of these registrations to meet special requirements or improve performance: builder.Register(c => new HomeController(Settings.SiteName)).FactoryScoped();
|
Could anybody be pleased to send me the real sample of autofac configuring with xml becaule all the authors rely on theirs intuition doing that but i have not that, and in this website is described about it very pure.
My email: mytestmailbox@ukr.net.
Thank you in advance.
Code above should read:
builder.Register<MyFoo>() .WithArguments( new NamedParameter("message"), "Hello!"), new NamedParameter("meaning"), 42));I think it should actually read...:
builder.Register<MyFoo>() .WithArguments( new NamedParameter("message", "Hello!"), new NamedParameter("meaning", 42));