I am using Autofac 2.4.5.724 under vb.net 2010. I have several classes without default constructors that I want autofac to resolve, and I want to register them using RegisterAssemblyTypes (not registering the classes one by one). Is it possible?
My interface is like this:
Namespace Repo
Public Interface IPeople
Function All() As IList(Of RCO.People)
End Interface
End Namespace
The implementation is like this:
Namespace Repo
Public Class People
Inherits Base
Implements IPeople
Public Sub New(ByVal cs As String)
MyBase.New(cs)
End Sub
Public Function All() As IList(Of RCO.People) Implements IPeople.All
...
End Function
End Class
End Namespace
I can register the classes one by one like this:
Dim builder = New ContainerBuilder
builder.Register(
Function(x) New MyLib.Repo.People("Data Source=localhost...")
).As(Of MyLib.Repo.IPeople)()
Dim container = builder.Build
Dim peep = container.Resolve(Of MyLib.Repo.IPeople)()
But I don’t want to register the classes one by one, I want autofac to scan my assembly:
Dim builder = New ContainerBuilder
builder.RegisterAssemblyTypes(Reflection.Assembly.Load("MyLib")).Where(
Function(x) x.Namespace = "Repo").AsImplementedInterfaces() ...what else?...
Dim container = builder.Build
Dim peeprepo = container.Resolve(Of ReportCenterLib.Repo.IPeople)()
Alternatively, can I put constructor parameter during resolve?
Dim peeprepo = container.Resolve(Of ReportCenterLib.Repo.IPeople)(...here?...)
You can definitely specify the parameter when resolving. You just need to add one or more TypedParameters created using the actual parameters to the Resolve call; you can’t pass them directly:
Now, when Autofac sees a constructor for the registered type that accepts a string, it will substitute the given parameter. Understand that Autofac will get confused if you have a constructor that takes multiple strings; in that case, you’ll need to specify each string as a named parameter which Autofac will match to the constructor parameter names. This has its own complexities; see the SO question here: Autofac parameter passing