Is it possible to resolve a service in autofac without registering it with the container?
So far I have come up with something like this:
public object ResolveUnknownService(IContainer container, Type serviceType)
{
ILifetimeScope lifetimeScope = container.BeginLifetimeScope(b => b.RegisterType(serviceType).ExternallyOwned());
try
{
return lifetimeScope.Resolve(serviceType);
}
finally
{
lifetimeScope.Dispose();
}
}
It works, but I am a bit worried about performance. I also don’t want to use AnyConcreteTypeNotAlreadyRegisteredSource beacuse I want to be specific about which services I want (or don’t want) to resolve this way.
In your example, disposing the temporary lifetime scope will dispose the object being returned as well as any of its dependencies; components only live as long as the lifetime scope that they were resolved from.
Are there any known criteria that identifies these types? There is an overload of the
AnyConcrete...class’s constructor that can specify a filter on what it will resolve. If there are such criteria though thenRegisterAssemblyTypes()is almost always a better option.(Unless you’re integrating with a legacy/third-party framework then this pattern is probably not the best way to use Autofac, as it leads down the Service Locator path. YMMV of course.)