Wednesday, March 19, 2014

[.NET] For reference, StructureMap basic setup

The StructureMap xml should look like this for several mappings:

<?xml version="1.0" encoding="utf-8" ?>
<StructureMap>
  <DefaultInstance
    PluginType="LoginExample.Domain.Interfaces.Repositories.IUserRepository,
        LoginExample.Domain.Interfaces"
    PluggedType="LoginExample.Infrastructure.TestDataAccess.TestUserRepository,
        LoginExample.Infrastructure.TestDataAccess" />
  <DefaultInstance
    PluginType="LoginExample.Domain.Interfaces.Services.ILoginService,
        LoginExample.Domain.Interfaces"
    PluggedType="LoginExample.Services.LoginService,
        LoginExample.Services" />
  <DefaultInstance
    PluginType="LoginExample.Domain.Interfaces.Services.IAuthenticationService, LoginExample.Domain.Interfaces"
    PluggedType="LoginExample.Services.AuthenticationService, LoginExample.Services" />
</StructureMap>

Below are contents of the Bootstrapper. Use the Run method in Global.asax.

// StructureMap ContollerFactory
    public class StructureMapControllerFactory : DefaultControllerFactory
    {
        protected override IController
            GetControllerInstance(RequestContext requestContext,
            Type controllerType)
        {
            try
            {
                if ((requestContext == null) || (controllerType == null))
                    return null;

                return (Controller)ObjectFactory.GetInstance(controllerType);
            }
            catch (StructureMapException)
            {
                System.Diagnostics.Debug.WriteLine(ObjectFactory.WhatDoIHave());
                throw new Exception(ObjectFactory.WhatDoIHave());
            }
        }
    }

    public static class Bootstrapper
    {
        public static void Run()
        {
            ControllerBuilder.Current
                .SetControllerFactory(new StructureMapControllerFactory());

            ObjectFactory.Initialize(x =>
            {
                x.AddConfigurationFromXmlFile("StructureMap.xml");
            });
        }
    }

No comments:

Post a Comment