ASP.NET MVC Core: The Good Parts

MVC 6 should be out any day, so we need to be prepared.

The good thing is, it’s all very similar to MVC 5; the even better thing is, it got better! A couple of ways it is so cool, in my mind, are:

  • Most of the stuff is very similar to what we had: controllers, views, mostly work the same way;
  • MVC and Web API have been merged together, so it’s not really any different add an API controller that returns JSON or an MVC controller that returns an HTML view;
  • All of its code is available in GitHub, and you can even contribute to it;
  • It is now cross-platform, meaning, you will be able to deploy your web app to Linux (even as a Docker container) and Mac (if you use .NET Core);
  • It is very modular: you only add to your project the Nuget packages you really need;
  • It now uses service providers to resolve all of its features; you do not need to know the static location of properties, like, ControllerBuilder.Current, GlobalFilters.Filters, etc; the boilerplate configuration in the Startup class is pretty easy to follow and change;
  • The default template has Bower, NPM and Gulp support out of the box;
  • No need to explicitly add attribute routing, it is built-in by default;
  • We have a better separation of contents and code, in the form of the wwwroot folder to which servable contents are moved;
  • Logging is injected, as are most of the services we need, or we can easily add our own without the need to add any IoC library; even filters can come from IoC;
  • It is now possible to have our Razor pages inherit from a custom class, have custom functions defined in Razor (by the way, do not use it!) and inject components into it;
  • View components and tag helpers are a really cool addition;
  • The new OWIN-based pipeline that is now ASP.NET is much more extensible and easy to understand than System.Web-based ASP.NET used to be;
  • This one is a corollary from the latter: Web.config is gone; let’s face it, it was a big beast, so it’s better to just drop it.

On the other hand, we will need to learn a lot of new stuff, namely, a whole lot of new interfaces and base classes to use. Also, it may sometimes be a bit tricky to find out which Nuget package contains that specific API we’re after. And because there is no more System.Web, all of the infrastructure management is very different. Finally, not all the libraries we’re used to will be immediately available for .NET Core, but that’s really not a problem with ASP.NET Core itself.

All in all, I think it is a good thing! I’ll be talking more on ASP.NET Core, so stay tuned!

Implementing Missing Features in Entity Framework Core – Part 4: Conventions

Conventions

This will be the fourth in a series of posts about bringing the features that were present in Entity Framework pre-Core into EF Core. The others are:

  • Part 1: Introduction, Find, Getting an Entity’s Id Programmatically, Reload, Local, Evict
  • Part 2: Explicit Loading
  • Part 3: Validations

Conventions are a mechanism by which we do not have to configure specific aspects of our mappings over and over again. We just accept how they will be configured, of course, we can override them if we need, but in most cases, we’re safe.

In EF 6.x we had a number of built-in conventions (which we could remove) but we also had the ability to add our own. In Entity Framework Core 1, this capability hasn’t been implemented, or, rather, it is there, but hidden under the surface.

A lot has changed. As of Entity Framework Core, conventions are specific to the provider in use, which makes perfect sense. But then we have several kinds of conventions. Just to give you an idea, the ConventionSet class exposes 15 convention collections! This is the place where we can register our own conventions, but there are two problems:

  • The current ConventionSet instance is not publicly accessible, so we need to use reflection to get hold of it;
  • We don’t want to add a new “blank” instance of ConventionSet because this way we would lose all of the conventions that would have been injected by the provider.

So, the solution I came up with had to use reflection to get the current convention set and allow adding new conventions, which is not ideal. Let’s see the code.

We need an extension method to get hold of the ConventionSet from the ModelBuilder and allow adding a convention, in the form of a IModelConvention:

public static class ModelBuilderExtensions

{

    public static ModelBuilder AddConvention(this ModelBuilder modelBuilder, IModelConvention convention)

    {

        var imb = modelBuilder.GetInfrastructure();

        var cd = imb.Metadata.ConventionDispatcher;

        var cs = cd.GetType().GetField("_conventionSet", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(cd) as ConventionSet;

 

        cs.ModelBuiltConventions.Add(convention);

 

        return modelBuilder;

    }

 

    public static ModelBuilder AddConvention<TConvention>(this ModelBuilder modelBuilder) where TConvention : IModelConvention, new()

    {

        return modelBuilder.AddConvention(new TConvention());

    }

}

Feel free to cache the _conventionSet field somewhere, but that is not the point of this post.

You can see that we are adding the new convention to the ModelBuiltConventions collection, basically, because this is the only collection that Entity Framework Core will go through during the OnModelCreating method, all of the other collections will have been processed before it. We’re cool with that.

Let’s see two examples of sample conventions, first, one to set the maximum length of strings, where it hasn’t been explicitly set:

public sealed class DefaultStringLengthConvention : IModelConvention

{

    internal const int DefaultStringLength = 50;

    internal const string MaxLengthAnnotation = "MaxLength";

 

    private readonly int _defaultStringLength;

 

    public DefaultStringLengthConvention(int defaultStringLength = DefaultStringLength)

    {

        this._defaultStringLength = defaultStringLength;

    }

 

    public InternalModelBuilder Apply(InternalModelBuilder modelBuilder)

    {

        foreach (var entity in modelBuilder.Metadata.GetEntityTypes())

        {

            foreach (var property in entity.GetProperties())

            {

                if (property.ClrType == typeof(string))

                {

                    if (property.FindAnnotation(MaxLengthAnnotation) == null)

                    {

                        property.AddAnnotation(MaxLengthAnnotation, this._defaultStringLength);

                    }

                }

            }

        }

 

        return modelBuilder;

    }

}

Easy, easy, hey? We go through all of the mapped entities, then through all of their properties of type string, check if the maximum length annotation is present, and, if not, add a new one. Only one method, with access to all mapped entities.

Another example, turning off the table pluralization. As you know, as of EF RC2, table names of DbSet properties exposed in the DbContext are pluralized. We can get rid of this behavior if we explicitly set the name to something, in this case, it will be the entity type name:

public sealed class SingularizeTableNameConvention : IModelConvention

{

    public InternalModelBuilder Apply(InternalModelBuilder modelBuilder)

    {

        foreach (var entity in modelBuilder.Metadata.GetEntityTypes())

        {

            if (entity.FindAnnotation(RelationalAnnotationNames.TableName) == null)

            {

                entity.Relational().TableName = entity.Name.Split('.').Last();

            }

        }

 

        return modelBuilder;

    }

}

Now, some new extension methods come handy:

public static ModelBuilder UseDefaultStringLength(this ModelBuilder modelBuilder, int defaultStringLength = DefaultStringLengthConvention.DefaultStringLength)

{

    modelBuilder.AddConvention(new DefaultStringLengthConvention(defaultStringLength));

 

    return modelBuilder;

}

 

public static ModelBuilder UseSingularTableNames(this ModelBuilder modelBuilder)

{

    modelBuilder.AddConvention<SingularizeTableNameConvention>();

 

    return modelBuilder;

}

And that’s it! The way to apply these conventions (one or both) is during OnModelCreating:

protected override void OnModelCreating(ModelBuilder modelBuilder)

{

    modelBuilder

        .UseDefaultStringLength()

        .UseSingularTableNames();

 

    base.OnModelCreating(modelBuilder);

}

You can now reuse these conventions in all of your context classes very easily. Hope you enjoy it! Two final remarks about this solution:

  • The reflection bit is a problem, because things may change in the future. Hopefully Microsoft will give us a workaround;
  • There is no easy way to remove built-in (or provider-injected) conventions, because are applied before OnModelCreating, but I think this is not a big problem, since we can change them afterwards, as we’ve seen.

Stay tuned for more!

Implementing Missing Features in Entity Framework Core – Part 3

Back after a few weeks. For those who don’t know, this series of posts is dedicated to bringing some of the futures that existed in Entity Framework but were dropped in Core. You can find the first post here and the second here.

This time, an often forgotten feature that didn’t made it to Core: entity validation. Most of the posts that talk about what’s new usually forget about validation having been left out.

In a nutshell, Entity Framework used to validate entities according to the System.ComponentModel.DataAnnotations API:

It’s simple to get these back, though. All you need to do is override SaveChanges and plug in the validation code for all new and modified entries:

public class MyContext : DbContext

{

    public override int SaveChanges(bool acceptAllChangesOnSuccess)

    {

        var serviceProvider = this.GetService<IServiceProvider>();

        var items = new Dictionary<object, object>();

        

        foreach (var entry in this.ChangeTracker.Entries().Where(e => (e.State == EntityState.Added) || (e.State == EntityState.Modified))

        {

            var entity = entry.Entity;

            var context = new ValidationContext(entity, serviceProvider, items);

            var results = new List<ValidationResult>();

 

            if (Validator.TryValidateObject(entity, context, results, true) == false)

            {

                foreach (var result in results)

                {

                    if (result != ValidationResult.Success)

                    {

                        throw new ValidationException(result.ErrorMessage);

                    }

                }

            }

        }

 

        return base.SaveChanges(acceptAllChangesOnSuccess);

    }

}

The key here is the Validator class: it knows how to perform all these validations, including finding all validation attributes in the class and in each property. In case of an error, we just throw a ValidationException with the error message, and the saving is aborted.

ASP.NET Core Inversion of Control and Dependency Injection

Introduction

There are quite a few good posts out there on Inversion of Control (IoC) and Dependency Injection (DI) in the ASP.NET Core world, but I felt there was still something to be said, hence this post! Mind you, this is going to be a long one! I once wrote another post on the history of dependency resolution in .NET, you may want to have a look at it. Always keep in mind that this is based on the latest bits, and may still change when it gets to the final version.

Services Registration

At bootstrap, ASP.NET Core will either call the ConfigureServices method, or one with a name following the convention Configure<environment>Services, where <environment> comes from the Hosting:Environment environment variable, and you can also set it in Visual Studio:

image

It is commonly set to “Development”, “Production”, “Staging”, etc. Keep in mind that if the environment-specific method exists (e.g., ConfigureDevelopmentServices), then the generic one (ConfigureServices) is not called.

The Configure*Services method is passed an instance of IServiceCollection, which is where we get to store our service registrations, so that they can be used by ASP.NET Core further along the pipeline. A service registration needs three things:

  • A key type, normally an interface or an abstract base class;
  • A concrete implementation of the key type;
  • A lifetime.

The lifetime determines how many times the concrete implementation is going to be built. The ASP.NET Core service provider implementation knows about three different lifetimes:

  • Scoped: an instance is created the first time it is requested during the same HTTP request, and during that request, this same instance is always returned;
  • Singleton: an instance is created the first time it is requested, and this same instance is always returned in all subsequent calls;
  • Transient: a new instance is always created, whenever it is requested.

A registration is an instance of the ServiceDescriptor class that is added to the IServiceCollection instance:

services.Add(new ServiceDescriptor(typeof(IMyService), typeof(MyService), ServiceLifetime.Singleton));

There are several extension methods that make this registration even easier.

What if you want to have custom processing when a service is returned? Simple:

services.AddTransient<IMyService>(sp =>

{

    var something = sp.GetService(typeof(ISomething)) as ISomething;

    var other = new OtherService();

    //do something with it

    return new MyService(other);

});

Keep in mind that the concrete service must either implement or inherit from the key service. Also, for the Scoped lifetime, if the concrete class implements IDisposable, the service provider will honor it and call Dispose at the end of the HTTP request.

After Configure*Services, ASP.NET Core calls Configure, also in the Startup class. This is where the core initialization occurs, like, adding all middleware, such as the MVC one, that makes the application works the way we expect it. The Configure method can either have no parameters or it can receive one or more parameters with types that match the registered services. For example, we will always have IApplicationBuilder, IHostingEnvironment, ILoggerFactory, so we can add them as parameters together with our own:

public void Configure(

    IApplicationBuilder app,

    IHostingEnvironment env,

    ILoggerFactory loggerFactory,

    IMyService service)

{

    //do something with the services

}

It gives us a good chance to initialize them before the actual fun begins. If we want, we can also pass it just an instance of the dependency resolution service, represented by the IServiceProvider interface, which has been around since the early days of .NET. The ASP.NET Core service provider implements this interface, so having it here just means: “get me the service provider implementation so that I can retrieve services from it”:

public void Configure(IServiceProvider serviceProvider)

{

    var env = serviceProvider.GetService(typeof(IHostingEnvironment)) as IHostingEnvironment;

    var service = serviceProvider.GetService(typeof(IMyService)) as IMyService;

}

In the latest version of ASP.NET Core, there is no globally accessible reference to the built-in service provider, something known as the service locator, of bad reputation. If, for any reason you feel you need it, here is the place to store it. By the way, the Microsoft.Extensions.DependencyInjection package has some good strongly typed extension methods for IServiceProvider, make sure you include it.

Services

Each concrete service class itself can be dependency-injected: by default, it should be a concrete class and have a public parameter-less constructor; if, however, we want to inject dependencies into it, which also need to be registered in the service provider, we can have a constructor that takes these dependencies:

public class MyService : IMyService

{

    public MyService(IServiceProvider serviceProvider)

    {

        //get something from the service provider

    }

}

Notice the usage of IServiceProvider again. Another option is to have the constructor contain more concrete dependencies:

public class MyService : IMyService

{

    public MyService(ILoggerFactory loggerFactory)

    {

        //do something with the logger factory

    }

}

You can pass any number of parameters, of any type that is registered in the service provider, normally in one of the Configure*Services methods. If the specified service type is not registered, you get an exception at runtime.

Controllers

An MVC controller can have dependencies injected through its constructor, like I’ve shown for services:

public class HomeController : Controller

{

    public HomeController(IMyService service)

    {

        //do something with the service

    }

}

The same pattern applies: we can either declare a parameter as IServiceProvider or as a more specific type. It doesn’t matter if our controller inherits from Controller or is a POCO controller.

There was another dependency injection possibility with MVC controllers, which consisted in decorating public properties with a [FromServices] attribute: if a registration exists that matched the property’s type, it would be injected into the property just after the controller is constructed:

public class HomeController

{

    [FromServices]

    public IService Service { get; set; }

}

This is no longer possible, and the functionality was removed in DNX RC2, although it will still work in RC1. Forget about it.

By default, controller classes themselves do not come from the dependency resolution mechanism. You can achieve that, if, in Configure*Services, you call AddControllersAsServices, passing it either a Type or an Assembly collection:

services

    .AddMvc()

    .AddControllersAsServices(new[] { typeof(HomeController).GetTypeInfo().Assembly });

This allows you to do this:

services.AddSingleton<HomeController, SingletonHomeController>();

Each time MVC tries to build an HomeController, it will instead get the same SingletonHomeController. Note that I am not saying that you should do this, but I think you get the idea!

Filters

Filters in MVC allow you to intercept action method calls, results and exceptions, and do stuff before, after of instead of the real actions. You have global filters and attribute filters: global filters apply always, and attribute filters only apply in the scope where they are declared – a controller’s class or an action method. Filters themselves can have dependencies injected into them.

In order to declare global filters, you use one of the overloads of the AddMvc method, normally in the Configure*Services method, and registering the filter as a service:

services.AddMvc(mvc => mvc.Filters.AddService(typeof(GlobalFilter)));

MVC will try to resolve the filter type, if necessary, injecting it any dependencies, in the usual way:

public class GlobalFilter : IActionFilter

{

    public GlobalFilter(IMyService service)

    {

        //do something with the service

    }

 

    public void OnActionExecuted(ActionExecutedContext context)

    {            

    }

 

    public void OnActionExecuting(ActionExecutingContext context)

    {

    }

}

The other option for filters is attributes, but attributes require a public parameter-less constructor. The MVC team came up with an alternative for that, in the form of the ServiceFilterAttribute and TypeFilterAttribute attributes. Both receive a Type and the difference is that the first will try to resolve that type from the services registration and the last one will just instantiate it. Let’s see an example:

[ServiceFilter(typeof(GlobalFilter))]

public class HomeController : Controller

{

    [TypeFilter(typeof(SomeFilter))]

    public IActionResult Index()

    {

        //...

    }

}

So, GlobalFilter is retrieved from the services registration, and, if it is a filter, it will behave accordingly to the context where it is located, in this case, it is the whole controller. SomeFilter, on the other hand, is just instantiated and used, no need to have it registered. Don’t forget that types passed to ServiceFilterAttribute and TypeFilterAttribute have to implement one of the filter interfaces in namespace Microsoft.AspNet.Mvc.Filters otherwise an exception is thrown.

Models

Model classes are declared as parameters to action methods in an MVC controller. There’s a binding mechanism that fills their properties automatically, but we can also use dependency injection here.

First, the whole model can come from dependency injection:

public IActionResult Index([FromServices] IMyService service)

{

    //...

}

Or, at least, some properties of the model:

public IActionResult Update(Model model)

{

    //...

}

 

public class Model

{

    [FromServices]

    public IMyService Service { get; set; }

 

    //...

}

Views

MVC views can also take injected services, through the @inject directive:

@inject IMyService service;

 

<p>@service.Serve()</p>

View Components

View components, introduced in ASP.NET MVC Core, can also be injected in pretty much the same way as controllers:

public class MyServiceViewComponent : ViewComponent

{

    public MyServiceViewComponent(IMyService service)

    {

        //do something with the service

    }

    

    public string Invoke()

    {

        //...

    }

}

Tag Helpers

Tag helpers, like view components and controllers, also support constructor injection:

[HtmlTargetElement("service")]

public class ServiceTagHelper : TagHelper

{

    public ServiceTagHelper(IMyService service)

    {

        //do something with the service

    }

 

    public override void Process(TagHelperContext context, TagHelperOutput output)

    {

        //...

    }

}

Middleware

OWIN-style middleware are likewise injectable through the constructor:

public class ServiceMiddleware

{

    private readonly RequestDelegate _next;

    

    public ServiceMiddleware(RequestDelegate next, IMyService service)

    {

        this._next = next;

        //do something with the service

    }

    

    public Task Invoke(HttpContext httpContext)

    {

        //...

    }

}

Using a Custom IoC/DI Container

Now, you may not want to use the built-in service provider and use your own (Unity, Autofac, Ninject, TinyIoC, etc). That is certainly possible!

You need to change the signature of the Configure*Services method so as to return an IServiceProvider:

public IServiceProvider ConfigureServices(IServiceCollection services)

{

    services.AddMvc();

 

    services.AddTransient<IMyService, MyService>();

 

    return new MyIoCContainer(services.BuildServiceProvider());

}

The key here is to create an instance of the service provider we want to use, maybe leveraging on the one produced from the service collection (BuildServiceProvider method), and return it here. Of course, if it has more features and lifetimes than the default one, you are free to use them all. The only contract it has to comply to is that of IServiceProvider.

Dependency Resolution

While running your MVC application, you can explicitly ask for services registered in the global (the default or your own) service provider. The HttpContext class exposes a RequestServices property; here you will find the custom service provider that you returned in Configure*Services, or ASP.NET Core’s built-in one. Whenever you have a reference to the current HttpContext (controllers, view components, tag helpers, views, middleware, filters), you get it as well. The “old” ApplicationServices was removed in recent commits, so it won’t make it to the final version of ASP.NET Core and you shouldn’t be using it.

Conclusion

The dependency injection mechanism was substantially changed in ASP.NET Core. The only identical feature seems to be constructor injection, and it is understandable, since it’s what most people should be using anyway. Now every moving part of ASP.NET Core is injectable through the same mechanism, which I think is a good thing. The problems so far have been the relative instability in the ASP.NET Core, things have been changing a lot, and there is still no light at the end of the tunnel.

.NET Core Console Applications

Updated

.NET Core is not just for web apps, and some people tend to forget about it! Well, this post is about that! Smile

OK, let’s first create a “console” .NET Core app. In Visual Studio 2015, create a new project of type WebClass Library (Package):

image

After you do that, if you want to run your app inside VS, you need to change a few things. Go to project.json and change the library from dotnet5.4 to dnxcore50:

image

If you want to get information from the environment, you need to obtain a reference to the APIs that supply that information. So, add references to Microsoft.Extensions.DependencyInjection.Abstractions and Microsoft.Extensions.PlatformAbstractions (you can see that in the above picture).

Now, things get a bit weird… you need to do something rather dumb:

public class Program

{

    public static IServiceProvider ServiceProvider { get; private set; }


    public Program(IServiceProvider serviceProvider)

    {

        ServiceProvider = serviceProvider;

    }


    static void Main(string [] args)

    {

        var re = ServiceProvider.GetService<IRuntimeEnvironment>();        //for operating system, architecture and runtime info

        var ae = ServiceProvider.GetService<IApplicationEnvironment>();    //for application path, name, version, configuration info

    }

}

Some “context” services are available through the dependency injection framework, available as an IServiceProvider instance, but you can also get a pointer to them through the PlatformServices.Detault property:

var ae = PlatformServices.Default.Application;


var re = PlatformServices.Default.Runtime;

Here you will find these services:

  • IApplicationEnvironment: the application context
  • IRuntimeEnvironment: runtime context
  • IAssemblyLoaderContainer: for adding assembly loaders
  • IAssemblyLoadContextAccessor: a façade to the assembly loaders, for loading assemblies on demand
  • ILibraryManager: for introspecting the referenced libraries

You can see that the .NET Core team took the decision to inject these into the constructor of types that it builds, but the funny think is that there is no need for an actual instance of the Program class, as all the runtime needs is the static Main method! It seems a bit silly that we need to keep things in static fields, but I think they do not want to have static access points to these in the core framework, so it’s up to use how we are going to use them. Rest assured, the constructor will be called before Main!

Update: According to a Microsoft announcement here, from RC2 onwards, .NET Core will not support constructor injection in the Program class, so, the way to go will be through PlatformServices and CompilationServices. However, it still works in the DNX 1.0.0-rc2-16357 runtime.

If you need to use System.Console, which you will likely do, in a console, app, you need to add a reference to the System.Console Nuget package, for the dnxcore50 framework.

For more advanced stuff, like, for example, accessing databases – any database as long as it is SQL Server… – you need to add the System.Data.SqlClient Nuget package. The code looks exactly the same as it would in plain old .NET:

using (var con = new SqlConnection())

using (var cmd = con.CreateCommand())

{

    con.ConnectionString = @"Data Source=.\SQLEXPRESS; Integrated Security=SSPI";

    con.Open();


    cmd.CommandText = "SELECT GetUtcDate()";


    var now = (DateTime) cmd.ExecuteScalar();


    Console.WriteLine(now);

}

Finally, you need to add a command to it, so that you can actually run it. Add a command, say, “run”, to the commands section of project.json:

"commands": {

  "run": "My.ConsoleApp"

}

Here, My.ConsoleApp should the name (and folder) of your project, these should match.

And this is about it. If you want to pass parameters to your program, you can do so in the call to dnx, after the command:

dnx run this and that

this and that” will be passed as arguments to the Main method.

For running dnx, make sure your runtime is set appropriately, by using dnvm.

Enjoy .NET Core console! Winking smile

 

Using MEF in .NET Core

For those who don’t know, the Managed Extensibility Framework (MEF) is alive and well, and has been ported to .NET Core as Microsoft.Composition (source here). Not all of MEF has been ported, just MEF 2 (System.Composition), not MEF 1 (System.ComponentModel.Composition), meaning, we don’t have the catalogs, which included, among others, the ability to load types from assemblies in a directory.

Using MEF is straightforward, and this time I will not go into details. What I will show is how we can load types from files in a directory.

First, a sample usage might be:

var conventions = new ConventionBuilder();

conventions

    .ForTypesDerivedFrom<IPlugin>()

    .Export<IPlugin>()

    .Shared();

 

var assemblies = new[] { typeof(MyPlugin).GetTypeInfo().Assembly };

 

var configuration = new ContainerConfiguration()

    .WithAssemblies(assemblies, conventions);

 

using (var container = configuration.CreateContainer())

{

    var plugins = container.GetExports<IPlugin>();

}

Notice that we have to build the assemblies list ourselves.

Now, let’s load assemblies from a folder instead. We’ll create an extension method for that purpose:

public static class ContainerConfigurationExtensions

{

    public static ContainerConfiguration WithAssembliesInPath(this ContainerConfiguration configuration, string path, SearchOption searchOption = SearchOption.TopDirectoryOnly)

    {

        return WithAssembliesInPath(configuration, path, null, searchOption);

    }

 

    public static ContainerConfiguration WithAssembliesInPath(this ContainerConfiguration configuration, string path, AttributedModelProvider conventions, SearchOption searchOption = SearchOption.TopDirectoryOnly)

    {

        var assemblies = Directory

            .GetFiles(path, "*.dll", searchOption)

            .Select(AssemblyLoadContext.GetAssemblyName)

            .Select(AssemblyLoadContext.Default.LoadFromAssemblyName)

            .ToList();

 

        configuration = configuration.WithAssemblies(assemblies, conventions);

 

        return configuration;

    }

}

The key here is the AssemblyLoadContext class: this is what allows us to obtain an assembly from a file stream or a byte array. Notice that in .NET Core, things have changed significantly, and now we don’t have AppDomain or Assembly.LoadFrom, and assemblies are now loaded by an assembly loader, in a similar way to what Java does with class loaders.

So, now you can change the code to:

var path = @"c:\some\path";

 

var configuration = new ContainerConfiguration()

    .WithAssembliesInPath(path, conventions);

It even works for loading assemblies in all sub-folders.

Maybe I’ll write another post on MEF in the near future, so stay tuned!