Can't get Autofac to resolve ObservableCollection<string>
I don't have much programming experience, so sorry if this is an obvious question.
See the following code. Autofac can resolve ObservableCollection<int>, but not ObservableCollection<string>.
class Program
{
static void Main()
{
var builder = new ContainerBuilder();
builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource());
using (var container = builder.Build())
{
// This line works.
var x = container.Resolve<ObservableCollection<int>>();
// This line throws exception:
// DependencyResolutionException was unhandled:
// No constructors on type 'System.Char*' can be found
// with 'Public binding flags'.
var y = container.Resolve<ObservableCollection<string>>();
}
}
}
I'm using Autofac 2.4.2 for .NET 4.0.
Any ideas?
Update:
It seems the problem is caused by:
builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource());
I replaced it with:
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly());
builder.RegisterGeneric(typeof(ObservableCollection<>))
.As(typeof(ObservableCollection<>));
Now it works开发者_运维百科. But I still don't quite understand exactly why.
(sorry for my English)
The reason AnyConcreteTypeNotAlreadyRegisteredSource
acts this way is that ObservableCollection<string>
has a constructor that takes string
. Since string
is a concrete class type, the AnyConcreteTypeNotAlreadyRegistereSource
will pick this up and try to resolve it. System.String
however doesn't have any constructors that are callable, so you get the exception you are experiencing.
If you're just getting started with Autofac, I'd strongly recommend against ACTNARS
- it only has a few use cases and most of them require the predicate
parameter to be provided to avoid unexpected behaviour like the above.
What you've got now is the best way to go. A couple of pointers - the As()
declaration is not necessary when the service type is the same as the concrete component type. Also, it is uncommon for ObservableCollection<T>
to be used as a service at all - if you can provide some more details on your scenario, there might be a better way to express it with Autofac.
精彩评论