I’ve just starting using Autofac DI for the first time on a large production project. I currently have it do registration and resolving for “normal” situations in Asp.Net MVC3. By this, I mean controllers, business layer, repositories, etc.
My problem is that I have 50+ classes that all have the same interface. I could give each class a unique interface type, but the problems with that approach are:
- It is extremely tedious as the methods are all exactly the same across all classes
- This seems to violate all the DRY principles of coding.
The usage is as a reference to the class to be instantiated on a MVC3 Custom attribute in our view models. Usage is:
[CustomAttribute(typeof(foo))]
Public string FooProperty {get;set;};
This attribute is then used in a custom MVC3 HTML Helper method and gets the fully qualified type name (or can be a System.Type) to use from the [CustomAttribute(typeof(foo))] attribute. From the name of the class to instantiate, the Html.Helper method requests the class to be instantiated. Before we added DI to the application, we had this working by using System.Activator.CreateInstance.
This approach was taken because it solves problems in other parts of the application where the attribute information is reused.
When I’ve looked at a number of ways to do this and am seriously confused as to the correct approach to take. Some guidance would be appreciated.
You are not required to resolve interfaces from an Autofac container, you can also resolve concrete classes. It depends on the type registration. You could bulk register your 50+ classes by looking for types implementing your special interface, and then register these classes by “self”:
AsSelfmakes sure that you are able to resolve by the class name, like this: