Nico Nico - 23 days ago 8
C# Question

MVC 6 RC2 Controllers in another assembly

In MVC 6 RC1 we used the

IAssemlbyProvider
interface to register assemblies that were discovered at runtime and inject additional controller types, in a similar fashion to this post.. Now with RC2 release the
IAssemblyProvider
has been removed and has changed to (see reference).

Our framework version is currently
net46
.

Since the upgrade our controllers in external assemblies (not referenced) are returning a
404
status.

We have tried manually add the controller to the registered controllers via the
ApplicationPartManager
.

var mvcBuilder = services.AddMvc();
var controllerFeature = new ControllerFeature();
mvcBuilder.PartManager.PopulateFeature(controllerFeature);

var moduleControllers = ModulesManager.GetControllers();
foreach (var c in moduleControllers)
controllerFeature.Controllers.Add(c);

mvcBuilder.PartManager.PopulateFeature(controllerFeature);


and...

services.AddMvc().ConfigureApplicationPartManager(app =>
{
var controllerFeature = new ControllerFeature();
app.PopulateFeature(controllerFeature);

var moduleControllers = ModulesManager.GetControllers();
foreach (var c in moduleControllers)
controllerFeature.Controllers.Add(c);

app.PopulateFeature(controllerFeature);
});


Now the assemblies are definitely loaded into the
AppDomain
as our dependency injection system is finding and populating services for other items in the external assemblies.

With our previous implementations this worked nicely using the
IAssemblyProvider
.

public class ModuleAwareAssemblyProvider : IAssemblyProvider
{
private readonly DefaultAssemblyProvider _defaultProvider;

public ModuleAwareAssemblyProvider(DefaultAssemblyProvider defaultProvider)
{
_defaultProvider = defaultProvider;
}

public IEnumerable<Assembly> CandidateAssemblies
{
get
{
return _defaultProvider.CandidateAssemblies.Concat(ModulesManager.Assemblies).Distinct();
}
}
}


I understand RC2 is still relatively new but if anyone has any experience registering additional controllers at start-up would be helpful.

Cheers, Nico

Answer

After some time spending working with the ControllerFeature directly with no result it was time to go back to basics.

Basically at start up of the application controllers are registered into the controller feature container not from the controller feature. This is key, as you need to get the controllers registered.

I was browsing the GitHub repository for RC2 and came across the ControllerFeatureProvider. As stated.

Discovers controllers from a list of <see cref="ApplicationPart"/>

And then has a method further down to PopulateFeature where we can see it grabs all the parts registered to the application and extracts the controller interfaces (the IsController() method is worth a review).

/// <inheritdoc />
public void PopulateFeature(
    IEnumerable<ApplicationPart> parts,
    ControllerFeature feature)
{
    foreach (var part in parts.OfType<IApplicationPartTypeProvider>())
    {
        foreach (var type in part.Types)
        {
            if (IsController(type) && !feature.Controllers.Contains(type))
            {
                feature.Controllers.Add(type);
            }
        }
    }
}

So now we know how the controllers are found, they come from an ApplicationPart registered to the application. Next question was how do we create an application part.

After some review and trying to use dependency injection, manually adding the part to the application to get my parts registered I came across another concept.

The interface IMvcBuilder has the extension method AddApplicationPart which adds an Assembly to the application parts. This is done by wrapping the assembly in an AssemblyPart application part. On review of the AssemblyPart this part returns all of the types found in the assembly to the calling part system (in our case the ControllerFeatureProvider).

/// <inheritdoc />
public IEnumerable<TypeInfo> Types => Assembly.DefinedTypes;

Now something interesting with the AssemblyPart is the method GetReferencePaths()

/// <inheritdoc />
public IEnumerable<string> GetReferencePaths()
{
    var dependencyContext = DependencyContext.Load(Assembly);
    if (dependencyContext != null)
    {
        return dependencyContext.CompileLibraries.SelectMany(library => library.ResolveReferencePaths());
    }

    // If an application has been compiled without preserveCompilationContext, return the path to the assembly
    // as a reference. For runtime compilation, this will allow the compilation to succeed as long as it least
    // one application part has been compiled with preserveCompilationContext and contains a super set of types
    // required for the compilation to succeed.
    return new[] { Assembly.Location };
}

It appears that the final piece of the puzzle is to enable preserveCompilationContext within the modules (or external assembly's) project.json file.

"preserveCompilationContext": {
    "type": "boolean",
    "description": "Set this option to preserve reference assemblies and other context data to allow for runtime compilation.",
    "default": false
}

Finally the implementation and resolution for this became quite simple. Each of our external assemblies (or modules) are loaded through our ModuleManager class. This has a list of all referenced module assemblies. So in the ConfigureServices method in the Startup.cs file where the MVC is registered we simply call the extension method AddApplicationPart for each module assembly as.

var mvcBuilder = services.AddMvc();
foreach(var module in ModulesManager.ReferencedModules)
{
    mvcBuilder.AddApplicationPart(module.ReferencedAssembly);
}

Once making these small changes my external controllers stopped returning a 404.