Autofac and autofac Chinese documents
Through Assembly scanning, You can automatically register the types that comply with the rules. This method is very convenient. This article introduces Assembly scanning.
I. Scanning
As mentioned above, this method is not complete.
First look at a previous method:
var builder = new ContainerBuilder();builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly());//.Where(n => n.Name.EndsWith("son"));var container = builder.Build();var person = container.Resolve<Person>();person.Self();var dog = container.Resolve<Dog>();dog.Say();
Ii. Filtering
If I do not want to register so many types, but want to register through the Assembly registration method, what should I do?
1. Where Filtering
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).Where(n => n.Name.EndsWith("son"));var container = builder.Build();var person = container.Resolve<Person>();person.Self();
You only need to add the Where method to filter the logs. After filtering, var dog = container. Resolve <Dog> () returns an error because it is not registered.
2. Sort t Filtering
Builder. registerAssemblyTypes (Assembly. getExecutingAssembly ()). struct T <Person> (); var container = builder. build (); // error // var person = container. resolve <Person> (); // person. self (); var dog = container. resolve <Dog> (); dog. say ();
There is a small note when using counter T.
Builder. registerAssemblyTypes (Assembly. getExecutingAssembly ()). country T <Person> (c => c. as <IPerson> (); var container = builder. build (); var person = container. resolve <IPerson> (); person. self (); // error // var personA = container. resolve <Person> (); // personA. self ();
We can see from the above that although the Person cannot be used directly, the Person instance can be obtained through IPerson.
3. Specify a service
At the time of registration, there was an As method, which has been seen before, that is, it has not been explained. In fact, it is to specify the service. However, in Assembly scanning, it is not ().
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).AsImplementedInterfaces();var container = builder.Build();var person = container.Resolve<IPerson>();person.Self();
Well, I actually called two constructors here. Don't worry. I used the previous code.
In the AsImplementedInterfaces () method, all services that comply with the rules are registered.