Tag Archives: MVC

Upgrading to MicroLite 6.0

There are a few changes in MicroLite 6.0 and some of the extensions which you need to be aware of when updating from a previous version.

The .NET 4.5 build now contains an Async version of the session api (IAsyncSession and IAsyncReadOnlySession). If you are using a .NET 4.5 app, I suggest you update to make full use of the async version. The MVC and WebApi extensions already exclusively make use of it (see further below for more details).

Here’s the .NET 4.5 async version of each session method:

.NET 4.0 API .NET 4.5 API
Read API
Session.Fetch(SqlQuery) await Session.FetchAsync(SqlQuery)
Session.Paged(SqlQuery) await Session.PagedAsync(SqlQuery)
Session.Single(obj) await Session.SingleAsync(obj)
Session.Single(SqlQuery) await Session.SingleAsync(SqlQuery)
Write API
Session.Delete(obj) await Session.DeleteAsync(obj)
Session.Insert(obj) await Session.InsertAsync(obj)
Session.Update(obj) await Session.UpdateAsync(obj)
Session.Advanced.Delete(Type, obj) await Session.Advanced.DeleteAsync(Type, obj)
Session.Advanced.Execute(SqlQuery) await Session.Advanced.ExecuteAsync(SqlQuery)
Session.Advanced.ExecuteScalar(SqlQuery) await Session.Advanced.ExecuteScalarAsync(SqlQuery)
Session.Advanced.Update(ObjectDelta) await Session.Advanced.UpdateAsync(ObjectDelta)

Attribute Mapping

If you use the attribute based mapping, the attributes are now in the MicroLite.Mapping.Attributes namespace rather than MicroLite.Mapping.

DbEncryptedString

The DbEncryptedString class and associated classes has moved to the new MicroLite.Extensions.Cryptography project

SQL Builder

The Delete and Update Builder WhereEquals method has been replaced with Where().IsEqualTo() to align it with the Select Builder

MicroLite.Extensions.Mvc

Method signature needs to change from:

public ActionResult MethodName(args)

to

public async Task<ActionResult> MethodName(args)

MicroLite.Extensions.WebApi

Method signature needs to change from:

public HttpResponseMessage Get(int id)

to

public Task<HttpResponseMessage> Get(int id)

example:

public Task<HttpResponseMessage> Get(int id)
{
    return this.GetEntityResponseAsync(id);
}
Advertisements

Unit Testing MVC Controllers

If you use the ASP.NET MVC Extension with ASP.NET MVC 4, you may encounter problems running unit tests if you inherit from the MicroLiteController or MicroLiteReadOnlyController.

This is because the MVC Extension for MicroLite is currently built against ASP.NET MVC 3.

Since the Controller classes in ASP.NET MVC 4 are backwards compatible with MVC 3, you can fix this by adding an app.config to your unit test project with a binding redirect for ASP.NET MVC as follows:

<runtime>
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <dependentAssembly>
      <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
      <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
    </dependentAssembly>
  </assemblyBinding>
</runtime>

New Infrastructure Interfaces

As part of MicroLite 3.0, two new interfaces were added to the MicroLite.Infrastructure namespace:

IHaveSession and IHaveReadOnlySession

These interfaces are implemented by the controllers in the ASP.NET MVC and ASP.NET WebApi extensions and the MicroLiteSessionAttribute for each extension checks against the interfaces rather than the base controllers.

This means that if you want to, you can use the extensions without having to inherit from the base controllers.

// Instead of having to do this:
public HomeController : MicroLiteController
{
...
}

// You can do this:
public HomeController : SomeOtherController, IHaveSession
{
...
}

This allows you to use the extensions in a scenario where you cannot control the base controller you are using or if you just don’t want to have to inherit from the base MicroLite controller for any reason.

MVC and WebApi extensions

If you use the MVC or WebApi extensions for MicroLite and you use an ISession or IReadOnlySession for every action (method) on your controllers, instead of applying the [MicroLiteSession] to each controller or method you can simply register it in GlobalFilters so that it is invoked for every controller action.

GlobalFilters.Filters.Add(new MicroLiteSessionAttribute());

You can still add a [MicroLiteSession] to specific controller actions if you want to use an Isolation Level or transaction style which differs from the default specified in GlobalFilters:

public class HomeController : MicroLiteController
{
    public ActionResult Index()
    {
        // For this action, this.Session will be resolved using the configuration of 
        // the MicroLiteSessionAttribute in GlobalFilters.
    }

    [MicroLiteSession(AutoManageTransaction = false)]
    public ActionResult Index2()
    {
        // For this action, we want to do something specific with the transaction so we add the
        // MicroLiteSessionAttribute to this method to override the default configuration.
        using (var transaction = this.Session.BeginTransaction())
        {
            ...
        }
    }
}

Using MicroLite with ASP.NET MVC

It is very easy to use MicroLite within ASP.NET MVC out of the box, however an extension package has been created to make it even easier.

To use it, firstly install the NuGet package Install-Package MicroLite.Extensions.Mvc

Then, in your application startup simply register the extension before creating the session factories.

protected void Application_Start()
{
    ... // common mvc startup, register routes etc.

    // Load the extension for mvc
    Configure
       .Extensions() // If you are also using a logging extension, that should be loaded first.
       .WithMvc();

    // Create the session factory...
    Configure
       .Fluently()
       ...
}

The extension includes a controller MicroLiteController which defines an ISession proeprty called Session, since the base controller class already defines a Session property, this has been redirected to a property called HttpSession. Inherit your controllers from MicroLiteController.

public class CustomerController : MicroLiteController
{
    ...
}

The extension also includes an ActionFilterAttribute called MicroLiteSessionAttribute. This can be applied to specific methods on your controller if only certain actions require an ISession or to the controller class if all methods require an ISession.

[HttpPost]
[MicroLiteSession]
public ActionResult Edit(int id, FormCollection collection)
{
    ...
}

or

[MicroLiteSession]
public class CustomerController : MicroLiteController

The attribute will ensure that a new ISession is created and assigned to the Session property of the controller before a method is called. It will also begin a transaction. Once the method has completed, it will either commit the transaction or if an exception was thrown within the method, it will roll the transaction back.

If you are using the automatic transaction management, it is important not to swallow exceptions inside your method, otherwise the transaction will not be rolled back. You should use error handler attributes to deal with exceptions which will allow the Mvc extension to properly manage the transaction.

If you want to opt out of the auto transaction management, simply initialize the attribute and set the property to false.

[MicroLiteSession(AutoManageTransaction = false)]

You should then begin and commit/rollback a transaction within the method yourself.

This article was written for version 1.2.2 of the MicroLite framework.