Reputation: 99
I am having a master data service which is a generic one. Example: IMasterDataService<T>
I am trying to build an Api controller for this in a similar fashion like MasterDataController<T>
. I want to resolve the controller using autofac, but I can't find any documentation for the same.
When I tried, I'm getting the error message as unable to resolve the type.
I am registering like builder.RegisterGeneric for the service, but controller I'm not getting instance and I would like to know if this is possible at all.
Upvotes: 0
Views: 339
Reputation: 4794
Well, anyways, you cannot resolve generic class at runtime. You need to parameterize it. This means that before resolving generic controller you must have a type to close this generic. The only reasonable source of said type that comes to my mind is the request itself, otherwise controller would not be generic, it just doesn't make sense to me. So, you'll need to craft your type using incoming request somehow, and then resolve your controller based on that type using some kind of custom controller factory or activator or whatever it is called in the framework you're using. In the .NET Core, for example, that would be IControllerActivator
, and you'll need to register controllers in the DI container using .AddControllersAsServices()
extension before doing that.
EDIT There's actually such an implementation for dotnet core right in the Microsoft's documentation. But they use slightly different technique: they do not actually register an open generic controller. They make all predefined variants of closed generic controllers and register them instead. I think that this is due to the fact that Microsoft's IoC container cannot resolve closed generic types from open generic registrations - at least it could not do that in .NET Core 1.x, I haven't tried it in 2.0 yet. However, it is possible with Autofac, so I think such an approach should work.
Another possibility here could be to inject IComponentContext
into non-generic controller and resolve master data service "on the fly" in the controller itself crafting the type needed to close generic right there in the controller.
Anyways, this is a generic answer to a generic question. If you need more detailed answer you'll need to provide more insight into what you're doing.
Upvotes: 1