NancyFx & Castle Windsor

I’ve just managed to fix a very odd problem with Castle Windsor and NancyFx. The error I was getting wasn’t much help at all really!

Can’t create component ‘Nancy.Routing.DefaultRouteCacheProvider’ as it has dependencies to be satisfied.
‘Nancy.Routing.DefaultRouteCacheProvider’ is waiting for the following dependencies:
– Service ‘System.Func`1[[Nancy.Routing.IRouteCache, Nancy, Version=0.22.2.0, Culture=neutral, PublicKeyToken=null]]’ which was not registered.

I’ve created a bootstrapper which among other this allows me to use a pre-existing container.

    public class NancyBootstrapper : WindsorNancyBootstrapper
    {
        private readonly IWindsorContainer _container;

        public NancyBootstrapper(IWindsorContainer container)
        {
            _container = container;
        }

        protected override IWindsorContainer GetApplicationContainer()
        {
            if (ApplicationContainer != null)
            {
                return ApplicationContainer;
            }

            _container.Kernel.Resolver.AddSubResolver(new CollectionResolver(_container.Kernel, true));
            _container.Register(Component.For<NancyRequestScopeInterceptor>());
            _container.Kernel.ProxyFactory.AddInterceptorSelector(new NancyRequestScopeInterceptorSelector());
            return _container;
        }

        protected override void RegisterBootstrapperTypes(IWindsorContainer applicationContainer)
        {
            // Note: Do NOT do the line below, this will cause the container to be registered twice and Windsor will throw an exception
            // applicationContainer.Register(Component.For<INancyModuleCatalog>().Instance(this));
        }
    }

Thanks to Ricardo Campos for getting me started! But whenever I tried starting nancy in self-host mode I immediately got the “missing IRouteCache” problem.

            var bootstrapper = _container.Resolve<INancyBootstrapper>();

            var uri = WebServerUri;
            _nancyHost = new NancyHost(uri, bootstrapper);

After much googling, head scratching, silent cursing and putting the world to rights a few times, I stumbled across a Stack Overflow answer. After reading through the link provided in the answer (https://github.com/NancyFx/Nancy.Bootstrappers.Windsor/pull/8). I tried adding the suggested fix.

        protected override void ConfigureApplicationContainer(IWindsorContainer existingContainer)
        {
            existingContainer.AddFacility<TypedFactoryFacility>();

            // some other cool stuff!
        }

Hey presto, it was all working and all is well with the world once more, until I hit the next bug that defies logic!

Advertisements

Using Moq to check the values of an object passed to a method

In order to test individual properties of an object passed to a method using Moq I have been making use of my Assert.IsFieldEqual method. See here for details.

Because I can’t call the Assert.IsFieldEqual inside a lambda, like so …


    _mockBus
        .Verify(x => x.Send(It.Is<MyMessage>(m => Assert.IsFieldEqual(m, propertyName, expectedValue))), Times.Once());

Obviously, since makes no sense as the Assert.IsFieldEqual is a void method. So, I’ve made use of Moq’s callback facility.


    MyMessage sentMessage = null;

    _mockBus
        .Setup(x => x.Send(It.IsAny<MyMessage>()))
        .Callback<object>((m) => sentMessage = (MyMessage) (((object[]) m)[0]));

    Assert.IsFieldEqual(sentMessage, propertyName, expectedValue);

This allows me to have a TestCase for each property in the message, so I have one test method for all the properties.

I’m all Moq’d out!

I’m currently working on creating a Hypermedia API, or at least getting as close as I can to one!

In order to avoid the client hitting a dead end when an error occurs, either internally within my code or as a result of a bad request from the client, I wanted to provide links that the client can follow. So, I created an ApiError model class to send in my response in such a case.

    [Hypermedia]
    public class ApiError : Resource
    {
        public string ParentId { get; set; }
        public string ErrorMessage { get; set; }
    }

The [Hypermedia] attribute is just a place holder I use within my Delegating Handler which “enriches” the resources with links. The ParentId is the id used in order to construct links to the home resource and it’s also used for constructing self links and so on.

The links are generated by way of Mark Seamann’s excellent HyprLinkr library, available via Nuget (http://nuget.org/packages/Hyprlinkr/).

My first attempt was to create an extension method to create the response, much like the built in HttpRequestMessage.CreateErrorResponse extension method. This worked great when I tested it using my current favourite chrome extension, POSTman. It returned the error, along with a “back” and “home” link so the client didn’t just hit a dead-end.

For example …

  "errorMessage" : "The was an error, run for the hills!",
  "_links" :
  [
    {
      "rel" : "home",
      "href" : "http://server/api/home/someone@example.com",
      "title" : "home",
      "verb" : "GET"
    }
  ]

So, all is well. I’m a happy bunny….

Until I run my unit tests.

What The Flip?

Why is there red everywhere?!

As it turns out I wrote some legacy (read: un-testable) code. Here’s what I’d come up with …

    public static class HttpRequestMessageExtensions
    {
        public static HttpResponseMessage CreateErrorResponse(
            this HttpRequestMessage request,
            HttpStatusCode statusCode,
            string parentId,
            string errorMessage,
            Action<IResourceLinker, ApiError> addLinks)
        {
            var apiError = new ApiError
            {
                ParentId = parentId,
                ErrorMessage = errorMessage
            };

            if (addLinks != null)
            {
                var routeLinker = _resourceLinkerFactory.GetResourceLinker(request);
                addLinks(routeLinker, apiError);
            }

            return request.CreateResponse(statusCode, apiError);
        }

After spending some time in the debugger trying to figure out why I was getting a null reference exception, I started looking at Mark’s code on github and eventually figured out that the GetRouteData() call was returning null. So, I spent more time trying to figure out a way of getting that to *not* be null. I ended up getting the source code for the aspnetwebstack from codeplex and looking at the code for GetRouteData().

Veering off-topic slightly, I didn’t have git installed on my pc, so I fired up powershell and …

  PS> cinst git

… I used chocolately to install it, restarted powershell and …

  PS> git clone https://git01.codeplex.com/aspnetwebstack

… I was rummaging around the asp.net web stack code 😀

Back on to topic …

After a few failed attempts at getting the null reference to go away it dawned on me that with another layer or two or abstraction I could Moq (on nuget too – https://www.nuget.org/packages/moq) my way out of trouble.

So, thinking about it for a little while I came up with a way of doing all this so I could moq it. Firstly I needed to change CreateApiErrorResponse from an extension method into a “service”, which I could then pass into the relevant controllers. Once I get past the unit test stage I could easily set it up using Castle Windsor. I would also need an IResourceLinker factory.

The Service

    public interface IHttpRequestMessageService
    {
        HttpResponseMessage CreateErrorResponse(
            HttpRequestMessage request,
            HttpStatusCode statusCode,
            string parentId,
            string errorMessage,
            Action<IResourceLinker, ApiError> addLinks);
    }

    public class HttpRequestMessageService : IHttpRequestMessageService
    {
        private readonly IResourceLinkerFactory _resourceLinkerFactory;

        public HttpRequestMessageService(IResourceLinkerFactory resourceLinkerFactory)
        {
            _resourceLinkerFactory = resourceLinkerFactory;
        }

        public HttpResponseMessage CreateErrorResponse(
            HttpRequestMessage request,
            HttpStatusCode statusCode,
            string parentId,
            string errorMessage,
            Action<IResourceLinker, ApiError> addLinks)
        {
            var apiError = new ApiError
            {
                ParentId = parentId,
                ErrorMessage = errorMessage
            };

            if (addLinks != null)
            {
                var routeLinker = _resourceLinkerFactory.GetResourceLinker(request);
                addLinks(routeLinker, apiError);
            }

            return request.CreateResponse(statusCode, apiError);
        }
    }

The Factory

    public interface IResourceLinkerFactory
    {
        IResourceLinker GetResourceLinker(HttpRequestMessage request);
    }

    public class ResourceLinkerFactory : IResourceLinkerFactory
    {
        public IResourceLinker GetResourceLinker(HttpRequestMessage request)
        {
            return new RouteLinker(request, new AttributeBasedRouteDispatcher());
        }
    }

Once I sorted out a few built errors it was time to do some Moqing…

    public class MyControllerTests
    {
        private Mock<IResourceLinkerFactory> _mockResourceLinkerFactory;
        private Mock<IResourceLinker> _mockResourceLinker;
        private IHttpRequestMessageService _httpRequestMessageService;
        private MyController _controller;

        [SetUp]
        public void SetUp()
        {
            const string id = "john.doe@example.com";

            var config = new HttpConfiguration();
            var request = new HttpRequestMessage(HttpMethod.Post, string.Format("http://localhost/api/user/{0}", id));

            _mockResourceLinkerFactory = new Mock<IResourceLinkerFactory>();
            _mockResourceLinker = new Mock<IResourceLinker>();
            _httpRequestMessageService = new HttpRequestMessageService(_mockResourceLinkerFactory.Object);

            _mockResourceLinkerFactory.Setup(x => x.GetResourceLinker(It.IsAny<HttpRequestMessage>()))
                                      .Returns(_mockResourceLinker.Object);

            _mockResourceLinker.Setup(x => x.GetUri(It.IsAny<Expression<Action<MyController>>>()))
                           .Returns(new Uri(string.Format("http://localhost/api/user/{0}", id)));

            _controller = new MyController(_httpRequestMessageService);
        }
    }

Hurrah! It all worked and I could get back to testing what I was actually trying to, which was unrelated to providing links when sending errors to the client. But, I needed this anyway 😀

Since the tests I was working on weren’t testing the presence of the links, I suppose I could have done something like this …

    var _mockHttpRequestMessageService = new Mock<IHttpRequestMessageService>();
    _mockHttpRequestMessageService
        .Setup(x => x.CreateErrorResponse(
            It.IsAny<HttpRequestMessage>(),
            It.IsAny<HttpStatusCode>(),
            It.IsAny<string>(),
            It.IsAny<string>(),
            It.IsAny<Action<IResourceLinker, ApiError>>())
        .Returns(new HttpResponseMessage(...));

Anyway, I hope that helps someone out. It’ll probably be me at some point in the future as my memory is not the best 😉

Displaying embedded web pages in Winforms

I had an application/plugin I wanted to display some license information in and also attribute my use of a public API. So, I figured a nice way to do that would be to drop a web browser control in my winform and then have an embedded resource as the content. So, I created a little webpage and set it’s Build Action to Embedded Resource. A tiny bit of css in the head section and it looked good.

But, I wanted to also display an image in there. I tried a few different ways, but eventually stumbled upon an answer on stackoverflow which suggested encoding the image as a Base64 string. So, I set to work creating a little helper method to load my embedded web page and automatically encode all images on it. I decided to go with using a placeholder to the image, like so …

%IMG("MyProgram.Images.logo.png")%

In order to find out the name of the resource, you may find running this little piece of code helpful …

var names = Assembly.GetExecutingAssembly().GetManifestResourceNames();

So, I used a little regex magic (courtesey of regexhero.net) to find those placeholders, extract the path and do the encoding for me.

    public static class EmbeddedWebPageLoader
    {
        public static string LoadWebPage(string name)
        {
            const string regexPattern = @"%IMG\(\""(?<ImagePath>[^\""]*)\""\)%";
            var assembly = Assembly.GetExecutingAssembly();
            var pageStream = assembly.GetManifestResourceStream(name);
            if (pageStream != null)
            {
                using (var webPageStreamReader = new StreamReader(pageStream))
                {
                    var pageContent = webPageStreamReader.ReadToEnd();
                    var matches = Regex.Matches(pageContent, regexPattern);
                    foreach (Match match in matches)
                    {
                        var imagePath = match.Groups["ImagePath"];
                        var extension = Path.GetExtension(imagePath.Value).Trim(".".ToCharArray());
                        var imageStream = assembly.GetManifestResourceStream(imagePath.Value);
                        if (imageStream != null)
                        {
                            var buffer = new byte[imageStream.Length];
                            imageStream.Read(buffer, 0, (int) imageStream.Length);
                            var imageBase64String = Convert.ToBase64String(buffer);
                            var imgTag = string.Format("<img src='data:image/{0};base64,{1}'/>", extension, imageBase64String);

                            pageContent = Regex.Replace(pageContent, regexPattern, imgTag);
                        }
                    }
                    return pageContent;
                }
            }
            return null;
        }
    }

It works like a dream, I can now use images inside my about box, like so …

webBrowser.DocumentText = EmbeddedWebPageLoader.LoadWebPage("MyProgram.About.html");

ASP.NET Web Api Validation with Data Annotations

I’ve recently moved a project over from WCF Web Api over to ASP.NET Web Api. In doing that I needed to re-implement my validation code. Thanks to the Api being a part of the MVC framework, things are much simpler now.

public class ValidationActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext context)
    {
        var modelState = context.ModelState;
        if (!modelState.IsValid)
        {
            dynamic errors = new JsonObject();
            foreach (var key in modelState.Keys)
            {
                var state = modelState[key];
                if (state.Errors.Any())
                {
                    errors[key] = state.Errors.First().ErrorMessage;
                }
            }

            context.Response = new HttpResponseMessage<JsonValue>(
                errors,
                HttpStatusCode.BadRequest);
        }
    }
}

All I need do now is decorate my models appropriately, for example …

public class TellAFriend
{
    [StringLength(100)]
    public string ToName { get; set; }

    [StringLength(100)]
    [Required]
    [RegularExpression(Regexes.EmailPattern, ErrorMessage = "Invalid email address")]
    public string ToEmailAddress { get; set; }
}

I will get a HTTP 400 response with a nice array of key/value pairs in the response body whenever a client sends me bad data.

{
    "ToEmailAddress": "Invalid email address"
}

ASP.NET Web Api Basic Authentication

I have recently moved a project over from WCF Web Api Preview 6 to ASP.NET Web Api (Beta). Part of that migration involved moving my message handler which dealt with authentication. In the old API I could only authenticate requests to the whole API or nothing at all. This is obviously not ideal, as we may want some parts of the API to be public, but other to only be available to authenticated users.

I have eventually come up with this for my message handler …

public class BasicAuthenticationMessageHandler : DelegatingHandler
{
    private readonly ILogger _logger;

    private class Credentials
    {
        public string Username { get; set; }
        public string Password { get; set; }
    }

    public BasicAuthenticationMessageHandler(ILogger logger)
    {
        _logger = logger;
    }

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
    {
        if (request.Headers.Authorization != null)
        {
            var credentials = ExtractCredentials(request.Headers.Authorization);
            if (credentials != null && ValidateUser(credentials))
            {
                var identity = new GenericIdentity(credentials.Username, "Basic");
                request.Properties.Add(HttpPropertyKeys.UserPrincipalKey, new GenericPrincipal(identity, new string[0]));
            }
        }
        return base.SendAsync(request, cancellationToken);
    }

    private bool ValidateUser(Credentials credentials)
    {
        if (!Membership.ValidateUser(credentials.Username, credentials.Password))
        {
            _logger.Debug("BasicAuthenticationMessageHandler.ExtractCredentials: Authentication failed for user '{0}'", credentials.Username);
            return false;
        }
        return true;
    }

    private Credentials ExtractCredentials(AuthenticationHeaderValue authHeader)
    {
        try
        {
            if (authHeader == null)
            {
                _logger.Debug("BasicAuthenticationMessageHandler.ExtractCredentials: auth header is null, returning null");
                return null;
            }

            if (authHeader.Scheme != "Basic")
            {
                _logger.Debug("BasicAuthenticationMessageHandler.ExtractCredentials: unsupported scheme {{0}), returning null", authHeader.Scheme);
                return null;
            }

            var encodedUserPass = authHeader.Parameter.Trim();
            var encoding = Encoding.GetEncoding("iso-8859-1");
            var userPass = encoding.GetString(Convert.FromBase64String(encodedUserPass));
            var parts = userPass.Split(":".ToCharArray());
            return new Credentials {Username = parts[0], Password = parts[1]};
        }
        catch (Exception ex)
        {
            _logger.Error(ex, "BasicAuthenticationMessageHandler.ExtractCredentials: Cannot extract credentials.");
            return null;
        }
    }
 }
 

To hook the handler into your API simply add the handler to the global configuration …

var logger = container.Resolve<ILogger>();
GlobalConfiguration.Configuration.MessageHandlers.Add(new BasicAuthenticationMessageHandler(logger));

The key thing to remember is to not try and take over the handling of returning the 401 (Unauthorised) response code to the client, let the framework do that for you via the [Authorize] attribute. Like so …

[Authorize]
public class MyController : ApiController
{
...
}

or, for individual actions …

public class MyController : ApiController
{
    [Authorize]
    public string Get(string id)
    {
    ...
    }
}

NUnit Assert extension to check any property of any object

I have just recently discovered the [TestCase] attribute of NUnit. With careful use it can drastically reduce the number of test methods you need to write. For my needs on a recent project I wanted to check field values which were being pulled from my database. What I’ve come up with is a simple extension to the NUnit Assert class which allows me to write test code such as …

[TestCase(0, "Forename", "Antony")]
[TestCase(0, "Surname", "Scott")]
[TestCase(0, "TwitterUserName", "antony_scott")]
public void ExampleTest(int index, string fieldname, object expectedValue)
{
    var result = GetPersonDetails();
    var list = result.ToList();
    Assert.IsFieldEqual(list.ElementAt(index), fieldname, expectedValue);
}

This gives me a very compact and easy to understand test with great visibility of any fields which are being pulled from the database correctly. All this is nothing new, as I’ve blogged about it previously here.

What I’ve added is the ability to dig into a structure like so …

[TestCase(0, "Forename", "Antony")]
[TestCase(0, "Surname", "Scott")]
[TestCase(0, "Twitter.UserName", "antony_scott")]
public void ExampleTest(int index, string fieldname, object expectedValue)
{
    var result = GetPersonDetails();
    var list = result.ToList();
    Assert.IsFieldEqual(list.ElementAt(index), fieldname, expectedValue);
}

In case you can’t see any difference, it’s the “dot” in the 3rd test case.

Here is the “extension” of the Assert class which makes it possible …

public class Assert : NUnit.Framework.Assert
{
    public static void IsFieldEqual(object obj, string propertyName, object expectedValue)
    {
        var type = obj.GetType();

        var dotIndex = propertyName.IndexOf('.');
        if (dotIndex != -1)
        {
            var innerObjName = propertyName.Substring(0, dotIndex);
            var innerPropName = propertyName.Substring(dotIndex + 1);
            var innerProp = type.GetProperty(innerObjName);
            var innerObj = innerProp.GetValue(obj, null);
            IsFieldEqual(innerObj, innerPropName, expectedValue);
        }
        else
        {
            var prop = type.GetProperty(propertyName);
            var actualValue = prop.GetValue(obj, null);
            AreEqual(expectedValue, actualValue);
        }
    }
}

Using Json.NET to generate JsonSchema

Actually generating the schema is pretty simple …

using Newtonsoft.Json.Schema;

var jsonSchemaGenerator = new JsonSchemaGenerator();
var myType = typeof(MyClass);
var schema = jsonSchemaGenerator.Generate(myType);
schema.Title = myType.Name; // this doesn't seem to get done within the generator

then write it to a file …

var writer = new StringWriter();
var jsonTextWriter = new JsonTextWriter(writer);
schema.WriteTo(jsonTextWriter);
dynamic parsedJson = JsonConvert.DeserializeObject(writer.ToString());
var prettyString = JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
var fileWriter = new StreamWriter("MySchema.txt");
fileWriter.WriteLine(schema.Title);
fileWriter.WriteLine(new string('-', schema.Title.Length));
fileWriter.WriteLine(prettyString);
fileWriter.Close();

What took me a while to figure out was that MyClass needs to be decorated with specific attributes in order for the schema to be correctly generated.

public class MyClass
{
    [JsonProperty(Required = Required.Always)]
    public string Forename { get; set; }

    [JsonProperty(Required = Required.Always)]
    public string Surname { get; set; }

    [JsonProperty(Required = Required.Always)]
    public string EmailAddress { get; set; }

    [JsonProperty(Required = Required.AllowNull)]
    public string MobilePhoneNumber { get; set; }
}

So, the JsonProperty attribute is your friend here! It took me a while to figure out, including some time stepping through the Json.NET source code in the debugger.

Reflection Based Assert with NUnit

I recently wrote about using reflection to check for null values in conjunction with the TestCase attribute. I’ve just taken this a step further by creating a derived Assert class …

public class Assert : NUnit.Framework.Assert
{
    public static void IsFieldEqual(object obj, string propertyName, object expectedValue)
    {
        var type = obj.GetType();
        var prop = type.GetProperty(propertyName);
        var actualValue = prop.GetValue(obj, null);
        AreEqual(expectedValue, actualValue);
    }
}

This allows me to write tests to check the value of each field in a result object and have the assert fail on the specific field, it also doesn’t stop the other field being tested. So, using the TestCase attribute I can write tests such as this …

[TestCase("Forename", "Antony")]
[TestCase("Surname", "Scott")]
public void example_test(string fieldname, object expectedValue)
{
    // Arrange
    Context.AddPerson(new Person { ID = 1, Forename = "Antony", Surname = "Scott" });

    // Act
    var result = Service.GetPerson(1);

    // Assert
    Assert.IsFieldEqual(result, fieldname, expectedValue);
}

Obviously this is an over-simplified example. But, the idea is that I can now have a complex object being loaded up by an integration test into my database. I then use a Service of some kind (what I’m testing) to query my database and I can then make sure all the correct details have been retrieved from the database.

Automatically Adding Entity Framework Config Classes to the Model Builder (Version 2)

I recently wrote about how to Automatically Add Framework Config Classes to the Model Builder. Since writing that post I have come across a situation where I was writing the exact same model class in a different application. That just didn’t smell right to me, since the other applications data access layer had been packaged up by nuget I could simply add a reference to it. That’s all well and good, but I didn’t want to have to go to any special effort to add the model configuration classes I needed to my modelbuilder. So, I’ve created a fairly simple (although it’s taken me a while to get it working how I want it) base class from which I can derive my context classes.

using System;
using System.Collections.Generic;
using System.ComponentModel.Composition.Hosting;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;
using System.IO;
using System.Linq;
using System.Reflection;

namespace Base.EntityFramework
{
    public abstract class BaseDbContext : DbContext
    {
        protected BaseDbContext() { }
        protected BaseDbContext(string connectionString) : base(connectionString) { }

        private IEnumerable<Type> GetTypes()
        {
            var type = typeof(EntityTypeConfiguration<>);
            return GetType()
                .GetProperties(BindingFlags.Instance | BindingFlags.Public)
                .Where(p => p.PropertyType.IsGenericType &&
                    p.PropertyType.GetGenericTypeDefinition() == typeof(IDbSet<>))
                .Select(p => type.MakeGenericType(p.PropertyType.GetGenericArguments().First()))
                .ToArray();
        }

        private static void LoadAllEntityConfigurationsFromAllAssemblies(DbModelBuilder modelBuilder, IEnumerable<Type> types, string assemblyFilter, IEnumerable<string> namePartFilters)
        {
            var path = Path.GetDirectoryName((new Uri(Assembly.GetExecutingAssembly().CodeBase)).AbsolutePath);
            new DirectoryCatalog(path, assemblyFilter)
                .LoadedFiles
                .Where(x =>
                {
                    var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(x.ToLower());
                    if (fileNameWithoutExtension != null)
                    {
                        var parts = fileNameWithoutExtension.Split(".".ToCharArray());
                        return parts.Any(part => namePartFilters.Any(namePartFilter => part == namePartFilter.ToLower()));
                    }
                    return false;
                })
                .Select(Assembly.LoadFrom)
                .ToList()
                .ForEach(assembly => assembly.GetTypes()
                .Where(t => types.Contains(t.BaseType))
                .Select(Activator.CreateInstance)
                .ToList<dynamic>()
                .ForEach(instance => modelBuilder.Configurations.Add(instance)));
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            var typesToLoad = GetTypes();
            LoadAllEntityConfigurationsFromAllAssemblies(modelBuilder, typesToLoad, "*.dll", new[] { "Data", "Domain" });
        }

    }
}

and in english ….

  1. Discover which classes for which I need to find and load the relevant EntityTypeConfiguration class. This is done with a little bit of reflection in the GetTypes() method.
  2. Use MEF to find the assemblies the config classes might be in. In this case it’s all of them (*.dll), but that could be changed to whatever is best for your situation.
  3. Use the namePartFilters to narrow down the list of assemblies further. In this case I’m looking for anything with “Data” or “Domain” in the filename (after it’s been split by periods).
  4. Load each assembly.
  5. Load any generic EntityTypeConfiguration types for the model classes used within my context class (the one which is derived from this base class).
  6. Instantiate each config class.
  7. Add it to the modelBuilder’s configurations.

Since this is a base class I can get this behaviour whenever I derive from it ….

public class DomainContext : BaseDbContext, IDomainContext
{
    public IDbSet<Employee> Employees { get; set; }

    public DomainContext() { }
    public DomainContext(string connectionString) : base(connectionString) { }

    IQueryable<Employee> IDomainContext.Employees { get { return Employees; } }
}

What this allows me to do is use models from any assembly I am referencing in my application and just add it to my Context. Any configuration class for it will then be automatically added to the model builder.