Showpitch Advanced Part 1: Using Neat Architecture for Domain Services

After 3 weeks of high level review of Showpitch we’re going to dive in to more advanced topics. This week we’re going to cover the specifics of using Neat Architecture for Showpitch.

Neat Architecture

Showpitch uses the Neat Architecture to allow for very rapid development and a great amount of flexibility and power. You can find the Neat Architecture in practice on GitHub, so check it out when you have a chance! Now let’s get in to what Neat Architecture is.

Neat Components

Neat starts with several important components, all from NuGet:

  • ASP.Net Web Api
    • Microsoft.AspNet.Cors.5.2.3
    • Microsoft.AspNet.WebApi.5.2.3
    • Microsoft.AspNet.WebApi.Client.5.2.3
    • Microsoft.AspNet.WebApi.Core.5.2.3
    • Microsoft.AspNet.WebApi.Cors.5.2.3
    • Microsoft.AspNet.WebApi.Tracing.5.2.3
    • Microsoft.AspNet.WebApi.WebHost.5.2.3
  • Microsoft Practices Unity 3
    • CommonServiceLocator.1.3
    • Unity.3.5.1404.0
    • Unity.Interception.3.5.1404.0
    • Unity.WebAPI.5.1
  • OData
    • Microsoft.AspNet.WebApi.OData.5.5.1
    • Microsoft.Data.Edm.5.6.0
    • Microsoft.Data.OData.5.6.0
    • System.Spatial.5.6.0
  • NLog
    • NLog.4.0.1
    • NLog.MongoDB.0.7.0
    • mongocsharpdriver.1.8.3
  • JSON.Net
    • Newtonsoft.Json.6.0.4
    • Newtonsoft.Json.7.0.1
  • Octopack
    • OctoPack.3.0.42
  • MongoRepository
    • MongoRepository.1.6.8
    • mongocsharpdriver.1.10.0

Neat Solution Structure

The Solution Structure is comprised of a pretty traditional N-Tier stack. This stack is broken out in to a few more layers to facilitate further decoupling and reduce friction among components.

  • Neat.Model – All Domain Models
  • Neat.Data – Common Data Access Definition
  • Neat.Data.Mongo – Mongo Data Access Implementation
  • Neat.Infrastructure – Components for Application Functionality
  • Neat.Application – Core Business Logic
  • Neat.Service – Orchestration of Business Logic Components
  • Neat.Infrastructure.WebApi – Web Api Specific Functional Components
  • Neat.Web.Api – Web Api Host

A Closer Look at Unity and IoC in Neat

In Neat we use a class called Bootstrapper in each project to configure all Type Registrations for that project. We then expose an Attach method in each Bootstrapper, allowing components that rely on that project to run that project’s configuration against that component’s Unity container. Here’s an example:

public static class Bootstrapper
{
    public static void Register()
    {
        var container = new UnityContainer();

        Register(container);
    }

    public static void Attach(IUnityContainer container)
    {
        Register(container);
    }

    private static void Register(IUnityContainer container)
    {
        Neat.Data.Mongo.Bootstrapper.Attach(container);
        Neat.Infrastructure.Bootstrapper.Attach(container);

        container.RegisterType(typeof (IDomainApplication<>),
            typeof (DomainApplication<>),
            new ContainerControlledLifetimeManager());

        container.RegisterAllService<IApplication>();
    }
}

There’s a lot happening in this code:

  • The Attach Method – Components that depend on this one pass their container in here so that this component can register its classes on the same container
  • The Two Attach Calls – This component in turn calls Attach on the components it depends on
  • The typeof Registrations – This is how to register the generic implementation so that any type passed to the generic results in a resolvable type. Using this registration pattern throughout the stack these components can handle any domain object from the Web Api through to the Database
  • RegisterAllService – This is an Unity Extension in Neat that registers every class as the default registration for its other interfaces when it has the marker interface specified
  • ContainerControlledLifetimeManager – This lifetime manager ensures that the type registered is resolved as a Singleton

A Closer Look at the Web Api Controller in Neat

The Controllers in Neat use the generic Domain stack to expose the Domain Models. Here’s an example:

public class NeatController : BaseReadWriteDeleteController<NeatExample>
{
    public NeatController(IDomainService<NeatExample> domainService)
        : base(domainService)
    {}
}

As you can see, using the Unity registration from before and this Controller pattern, we’re able to rapidly expose Api Services for new Domain Models. But where are the methods? The answer lies in the BaseReadWriteDeleteController:

public class BaseReadWriteDeleteController<T> : BaseApiController where T : class, IEntity<string>, new()
{
    private readonly IDomainService<T> _domainService;

    public BaseReadWriteDeleteController(IDomainService<T> domainService)
    {
        _domainService = domainService;
    }

    // GET api/{T}
    [EnableQuery]
    public IQueryable<T> Get()
    {
        return _domainService.GetAll();
    }

    // GET api/{T}/{id}
    public T Get(string id)
    {
        return _domainService.GetById(id);
    }

    // POST api/{T}
    public void Post([FromBody]T entity)
    {
        _domainService.Add(entity);
    }

    // PUT api/{T}
    public void Put([FromBody]T entity)
    {
        _domainService.Update(entity);
    }

    // DELETE api/{T}/{id}
    public void Delete(string id)
    {
        _domainService.Delete(id);
    }

    // GET api/{T}/getempty
    [HttpGet]
    public T GetEmpty()
    {
        return new T();
    }
}

This pattern works very well with MongoRepository due to its generic implementation. Perhaps in a future post we’ll cover an Entity Framework Code First approach for this.

This architecture allows for very rapid application development. To add a new Domain Service to this stack the steps are simply:

  1. Add a new Domain Model
  2. Add a new Controller and inherit from the appropriate Base Controller with the right methods
  3. Profit!

In future posts we’ll cover how to add additional behavioral capabilities in to this architecture and extend it with other service features. Is there a specific part of this architecture that you have questions about? Is there another part of Neat you saw on GitHub that you want me to write about next? Please leave a comment below to let me know! And keep checking back for more info about Showpitch and Neat!

<< Back to Showpitch 103
On to Showpitch Advanced Part 2 >>

Advertisement

Announcing Neat!

This week I want to talk about an Open Source project I’ve launched called Neat! When I say Open Source, I mean that this project is licensed under the MIT License, you can read this license in the LICENSE.txt file included with the project, or at the following URL – http://opensource.org/licenses/MIT

This project will contain many handy little infrastructure things that come in handy when working with .Net.

So far I’ve added a RESTful client object that greatly simplifies the work of calling and using responses from RESTful services. You’ll find this under the Neat.Service.Client.Rest namespace. I’ve also added some wrappers, generated using the technique covered last week, of some of the .Net components needed for the framework components that have been added. These are in the Neat.Wrapper namespace.

You can find the code for this project on GitHub at https://github.com/johnbrunnings/Neat. Contact me at me@johnbrunnings.com if you’d like to contribute.

Planned for this framework are the following features –

    • Encryption
      • SHA-512
      • MD5
      • AES (Rijndael)
    • Unity
      • Lifetime Handlers
        • WebContext
        • ServiceContext
    • Aspects
      • Logging
      • Performance
      • Feature Flag
      • Exception Handling
    • ServiceHosts & Factories (WCF)
    • Controller Factories
      • MVC 4
    • Random String Generation
    • Configuration Management
      • MsNetAppSettingsXml
      • MsNetCustomSettingsXml
      • MsNetConnectionStringsXml

Please contact me if you’d like to suggest anything as well.

Using ReSharper to Quickly Abstract Framework Components

I’m going to demonstrate today how to use ReSharper to quickly abstract even very large framework components. These might even be components that otherwise offer no abstract parent or interface with which to abstract their use as a dependency. This can be an important step to take when trying to properly unit test a given class or method.

We’ll begin by defining a wrapper class. Use the keyboard shortcut CTRL-ALT-INS to quickly and easily add a class.

01ReSharperAddFileFromTemplate

02ReSharperAddFileFromTemplateName

Once this class has been generated we then build the class’ constructor. ALT-INS brings up the code generation menu. Select “Constructor…” from the menu.

03ReSharperCodeGenerationConstructor

We then add the Wrapper’s dependency, which is the object we’re trying to abstract, as a parameter to the constructor. ALT-Enter to accept adding the using statement.

04ReSharperCodeGenerationConstructorParameterType

ALT-INS to bring up the code generation menu quickly.

05ReSharperCodeGenerationConstructorParameter

Then, using ReSharper, change this parameter to initialize a field which ReSharper will add. The keyboard shortcut here is ALT-Enter and then selecting the first option in the menu.

06ReSharperCodeGenerationConstructorField

07ReSharperCodeGenerationConstructorConstructed

Now that the private field has been added we need to generate the Delegating Members of the Wrapper. ALT-INS brings up the code generation menu. Select ”Delegating Members…” from the menu.

08ReSharperCodeGenerationDelegatingMembers

Be sure to select the entire list of members which will generate a complete Wrapper class implementation.

09ReSharperCodeGenerationSelectAllMembers

10ReSharperCodeGenerationSelectMembersGenerated

Now that there’s a complete Wrapper class we’ll use the Refactor method to extract an abstract parent class. The keyboard shortcut for this is CTRL-SHIFT-R. Select “Extract Superclass…” from the menu.

11ReSharperRefactorExtractSuper

Select all public methods on the class.

12ReSharperRefactorExtractSelectAllPublic

Then select all of the methods that were previously selected and make them abstract.

13ReSharperRefactorExtractMakeAllAbstract

Finally, unselect the constructor method and move forward.

14ReSharperRefactorExtractUnselectConstructor

This will generate the base class, which is now a successful abstraction from the framework component that the Wrapper wraps. And the Wrapper will inherit from this base class.

15ReSharperRefactorExtractInherits

16ReSharperRefactorExtracNewBase

Next we need a Factory to abstract the creation of this new Wrapper.

17ReSharperAddFileFromTemplate

18ReSharperAddFileFromTemplateName

Build the Factory to use the Wrapper and return it.

19ReSharperCreateFactoryUsingWrapper

Now give the Factory its own interface using the Refactor method. The keyboard shortcut for this is CTRL-SHIFT-R. Select “Extract Interface…” from the menu.

20ReSharperRefactorExtractInterface

Again select all public methods for the interface members.

21ReSharperRefactorExtractInterface

Generate the interface for the Factory for the final level of abstraction.

22ReSharperInterface

23ReSharperInterfaceDefined

And finally consume the framework component from the abstracted class which is returned by the new Factory. The new Factory can be injected by most mocking frameworks since it’s abstracted by an interface.

24ReSharperInterfaceUsed

By using this method, and relying on the Factory interfaces and abstract Wrapper base classes instead of the concrete objects, we better define our seams in our application and provide for true unit testing. And all while working around issues such as internal sealed classes and so forth that tend to be common enough in the framework so as to regularly cause a headache, especially with unit testing.