Loading Controller form App domain is very easy and MVC/Web
-Api can handle it by default. How to load controller from an assembly which is
build out of current project?
The use case might be like this: You want to use self
hosting for you Web-API application and you want to manually load all your assemblies
or you want to use some assembly from another project without adding the
controller file directly.
We can override default behavour of IAssemblyResolver with
our custom assembly resolver class. Here is the process to implement.
1)
Create one DLL project and add MVC/WebAPI . Here
is our simple controller
public class DataController : ApiController
{
public string Get()
{
return "Hello";
}
}
2)
Override default behavior of IAssemblyRsolver
public class CustomAssemblyResolver : IAssembliesResolver
{
public ICollection<Assembly> GetAssemblies()
{
List<Assembly> baseAssemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();
var controllersAssembly = Assembly.LoadFrom(@"C:\Controller.dll");
baseAssemblies.Add(controllersAssembly);
return baseAssemblies;
}
}
In this application I have kept
dll in C:\. GetAssembly() function will pick assembly from current app domain
at first and it will merge with Controller.dll.
3)
Replace IAssemblyResolver with
CustomAssemblyResolver
GlobalConfiguration.Configuration.Services.Replace(typeof(IAssembliesResolver), new CustomAssemblyResolver());
No comments:
Post a Comment