Getting #Unity Dependency Injection Working with ASP.NET 4.5.1

There are a lot of articles and blog posts out there about how to get Unity working with ASP.NET. After all of those, I found the best reference for doing this was the MSDN Unity documentation. However, there are a few things that you have to change in order to get it working with ASP.NET 4.5.1.

Here is a page on MSDN that describes what to do:

http://goo.gl/kOxwFo

However, in order to make this work, you will need to change the following lines in Web.config (in the <system.Web> element):

<httpModules>
  <add name="UnityModule" type="Unity.Web.UnityHttpModule, Unity.Web" />
  ... other HTTP modules defined here
</httpModules>

To use the following:

<system.webServer>
    <modules>
        <add name="UnityHttpModule" type="YOUR_NAMESPACE_HERE.UnityHttpModule, YOUR_PROJECT_DLL_HERE" />
    </modules>
</system.webServer>

This will load the correct HttpModule that will perform the dependency injection. This HttpModule is defined on this page:

http://goo.gl/pwXH5E

Don’t forget to follow all of the steps in the above document. This includes a link to the code for extending HttpApplication to allow you to retrieve the container.

http://goo.gl/97E768

I am also using Unity dependency injection with a WebAPI that is also in this project. I am using the same custom resolver with this, so I have created a Module that contains a public method for setting up the dependencies:

Module UnityRegistrationModule
    Public Sub RegisterTypes(ByRef container As IUnityContainer)
        container.RegisterType(Of ITestDtoRepository, TestRepository)(New HierarchicalLifetimeManager())
    End Sub
End Module

I can then call this method from the two places where dependencies need to be set up. That gives me a single place for setting up dependencies. In VB.NET, this is a module, this could be done in C# as a static method on a public Utility class.

Here is my WebAPIConfig that calls this method…

Public Module WebApiConfig
    Public Sub Register(ByVal config As HttpConfiguration)
        ' Web API configuration and services
        ' Set up dependency injection with Unity
        Dim container As New UnityContainer()
        RegisterTypes(container)
        
        config.DependencyResolver = New UnityResolver(container)

        ' Web API routes
        config.MapHttpAttributeRoutes()

        config.Routes.MapHttpRoute(
            name:="DefaultApi",
            routeTemplate:="api/{controller}/{id}",
            defaults:=New With {.id = RouteParameter.Optional}
        )
    End Sub
End Module

I had a little trouble getting all of this to work because my custom HttpModule was not executing. This is because I did not have it configured in the Web.Config correctly. After some messing around with the namespaces and project name, I was finally able to get it working.

Here is some code that uses a dependency from within a web page (the page has a label on it named “lblTest1″):

Public Class _Default
    Inherits Page

    <Dependency()> _
    Public Property _repository As ITestDtoRepository

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        lblTest1.Text = _repository.GetAll(Function(x) x.Id = "5c577a7a-13c4-4391-ab80-8ff567274d2e").SingleOrDefault().Description
    End Sub
End Class

As you can see, once you get the configuration correct, using dependencies from within an ASP.NET page is easy. Now, I can simply add a public property to the page of the desired interface and the DI resolver will inject an instance of it for me at runtime. All I have to do is code to the interface. If the required class changes in the future, all I have to do is associate the new class with the interface in the RegisterTypes() method. This is the beauty of dependency injection. I’m completely sold on this idea.

It took me a while to fully grasp the importance of DI, but now that I have, I can’t imagine life without it.

Using a Generic Func(Of TDto, Boolean) to retrieve data from a custom repository

I am using a custom Data Transfer Object framework in my design. As part of this, I am using the repository pattern to retrieve data from a data store. I will have multiple data stores of varying types, so I can’t just depend on Entity Framework for everything. This will mean a lot of extra work setting up repositories, but it will also give me the added benefit of using Dependency Injection for consuming repositories.

Here is my generic DtoRepository interface that my other repository interfaces will implement:

Public Interface IDtoRepository(Of TDto As DtoBase) : Inherits IDisposable
    Property Session As IUnitOfWork

    Function GetAll() As IList(Of TDto)
    Function GetAll(ByVal predicate As Func(Of TDto, Boolean)) As IList(Of TDto)
    Function Add(ByVal dto As TDto) As String
    Sub Delete(ByVal id As String)
    Sub Update(ByVal dto As TDto)
End Interface

This blog entry will focus on the GetAll(ByVal predicate As Func(of TDto, Boolean)) method and how I use it in my test repository.

Here is the implementation in my test repository:

    Public Function GetAll(predicate As Func(Of Models.TestDto, Boolean)) As IList(Of Models.TestDto) Implements IDtoRepository(Of Models.TestDto).GetAll
        ' create a temporary list to hold any matches
        Dim tList As New List(Of TestDto)

        ' loop through our list of dtos to see if we have a match
        For Each tempDto In _dtoList
            ' try to match the incoming query with the temp dto
            If predicate.Invoke(tempDto) Then
                ' it matched, so add it to our temporary list
                tList.Add(tempDto)
            End If
        Next

        ' the following is a short cut for the List. It is here for demo purposes to show how you can reuse the predicate
        'Return _dtoList.Where(predicate).ToList()

        ' return our temporary list containing all matches
        Return tList
    End Function

_dtoList is a local variable of List(Of TestDto) that contains the data for the test repository.

The code to look at here is the loop that goes through each of the DTOs in the data list and checks to see if we have a match. It does this by invoking the predicate that was passed in. We could have simply passed the predicate into the Where extension method on the List, but I wanted to demonstrate how you can Invoke a generic function to get the desired results for situations where you cannot pass the predicate into the data store. In the case of Entity Framework, I would simply pass this into the Where for my context.

Here is an example of how this method is being used:

   <TestMethod()> _
    Public Sub TestGetAllById()
        Dim testRepository As New TestRepository()

        Assert.AreEqual("Description2", _
                        testRepository.GetAll( _
                            Function(x) x.Id = "9b028687-2fda-4964-af92-836c0a4b13ec") _
                        .SingleOrDefault() _
                        .Description)
    End Sub

As you can see, we use a simple Lambda expression to ask for the DTO with the Id of

"9b028687-2fda-4964-af92-836c0a4b13ec"

Then we make sure that the Description matches what we expected.

Using the generic function in this way allows me to have a more dynamic and generic repository system that I can use with multiple data sources without having to do too much conversion for the ones that support predicates out of the box.

More #VB posts on the way

I recently started a new large project. Because of a client request, it will be developed entirely in VB.NET. So, from the core architecture all the way through the client code itself, everything will be in VB.NET. That means that a lot more posts on my blog will be about VB.NET topics and code samples.

Personally, I’m not all that worried, nor am I the least bit upset by this. My last projects had me maintaining legacy VB code written by someone else. This new project will be all new code written by me, so I’ll be the one to make sure it’s maintainable for the people that will follow behind me doing the maintenance.

I’m pretty excited. VB can do just about everything C# can do (no yield or anonymous methods – and I’ll miss the anonymous methods). I think the future of development is more in the framework changes and not so much in the language of choice. Microsoft is still improving VB.NET, so I don’t think they’ll abandon it any time soon.

So, look for more VB code samples and articles on this blog in the future.

It should still be relevant for .NET developers (including C# developers), as the core ideas and implementation will still be the same, it’s just a different language. I don’t think any C# developer will have trouble porting my VB samples to C# if they need the code.

Calling DataBind() on a GridView within an UpdatePanel to handle a row delete command

I was working on maintaining a site that used a GridView within an UpdatePanel and had difficulties with the DataBind() call. I added a delete button (using a CommandField) to the grid and wired up the command logic to delete from a generic list that I was keeping up with. The grid was bound to the List. It just wasn’t updating the contents of the Grid when I removed records from the source.

It turns out that when I added the Delete command, I was also supposed to handle the OnRowDeleting event. I didn’t receive an error message to let me know this until I removed the UpdatePanel and tried it again. Once I added the handler for the event, it worked just fine. So I added the UpdatePanel back and everything now works as it should.

C# 6 in action

Michael Earls:

I really like the Null propagation feature! C# 6.0 looks like it will be a winner for me.

Originally posted on Jon Skeet's coding blog:

Now that the Visual Studio 2015 Preview is available and the C# 6 feature set is a bit more stable, I figured it was time to start updating the Noda Time 2.0 source code to C# 6. The target framework is still .NET 3.5 (although that might change; I gather very few developers are actually going to be hampered by a change to target 4.0 if that would make things easier) but we can still take advantage of all the goodies C# 6 has in store.

I’ve checked all the changes into a dedicated branch which will only contain changes relevant to C# 6 (although a couple of tiny other changes have snuck in). When I’ve got round to updating my continuous integration server, I’ll merge onto the default branch, but I’m in no rush. (I’ll need to work out what to do about Mono at that point, too –…

View original 1,520 more words

How to implement IEquatable<T> correctly

Michael Earls:

Some great guidance on implementing comparisons on custom classes.

Originally posted on Technique:

Performing object value comparisons is an every-day occurence (for example, comparing an expected value with an actual value in a test assertion). However achieving true value comparison between two reference type objects is not as simple as you might think. To do it properly, you need to implement the IEquatable<T> interface, override two virtual methods of System.Object and implement two operators. That’s five methods in all!  This may seem like a lot of effort for something that is so simple with value types (i.e, structs) but you really don’t have any choice if you want to perform value comparisons on your class instances.

Here are the methods you need to implement/override:

  • IEquatable<T>.Equals
  • System.Equals
  • System.GetHashCode
  • operator ==
  • operator !=

I’ll describe each method in turn using an example class called Product which needs to support value comparisons but currently doesn’t.

First, implement the IEquatable<T> interface

This adds a single method called

View original 530 more words

#DotNet – Creating a generic extension of “Contains” to see if there’s something in a generic collection

Update: Added reference links at bottom of entry.

I was working with some code today and needed to see if a list of custom DTOs contained an object based on a string value I had. Here is my solution.

Some background…

Our Architecture uses a base abstract class called DtoBase:

    public abstract class DtoBase
    {
        public string Id { get; set; }
        public string Description { get; set; }

        public DtoBase() { }

        public string ToJson()
        {
            StringWriter w = new StringWriter();
            JsonSerializer s = new JsonSerializer();
            s.Serialize(new JsonTextWriter(w), this);
            return w.ToString();
        }
    }

All classes that derive from DtoBase have their own properties, but they all benefit from Json serialization using the ToJson method. This helps us in various ways in the application.

I am working with a generic list of a subclass of DtoBase (AccessoryGroup):

    public class AccessoryGroup : DtoBase
    {
        public bool QCFlag { get; set; }
    }

With this list, I wanted to see if it contained a DTO with an ID based on a given string. Unfortunately, the built-in Contains extension method on the list (in the System.Linq namespace) does not allow this behavior. It would require me to create an instance of AccessoryGroup containing the values I want to compare (and implement the IEquatable<T> interface on DtoBase. No big deal, but another requirement). What I needed was a version of the Contains extension method that let me pass in a string.

So, my first attempt was to create my own extension method using List as the type to extend:

        public static bool Contains(this List<DtoBase> list, string val)
        {
            foreach(DtoBase dto in list)
            {
                if dto.Id == val.Trim()
                {
                    return true;
                }
            }

            return false;
        }

Aside from the use of the foreach (which I refactored in the final code), this code did not work.

Here is some test code:

List<AccessoryGroup> accessoryGroupList = new List<AccessoryGroup>();
accessoryGroupList.Add(new AccessoryGroup { Id = "test", Description = "This is just test data" });

if(accessoryGroupList.Contains("test"))
{
    // this should be true
}

However, this code did not work. In fact, it didn’t even build. I got invalid arguments exceptions with my Contains call.

What to do? It then occurred to me that I’m working with a generic list, so I need to take a generic approach to this. Here’s the final code taht implements my new extension method as a generic method:

        public static bool Contains<TDto>(this List<TDto> list, string val) where TDto : DtoBase
        {
            return list.Any(a => a.Id.Trim() == val.Trim());
        }

Not only have I refactored to remove the ugly foreach loop, but I’ve converted the method to a generic method.

I thought I was going to have to write my code like this:

List<AccessoryGroup> accessoryGroupList = new List<AccessoryGroup>();
accessoryGroupList.Add(new AccessoryGroup { Id = "test", Description = "This is just test data" });

if(accessoryGroupList.Contains<AccessoryGroup>("test"))
{
    // this should be true
}

But I did not. It seems that because the accessoryGroupList is already a generic list of AccessoryGroup DTOs, it automatically knows that the Contains method will use the same type. Nice, huh?

So, my original code worked:

List<AccessoryGroup> accessoryGroupList = new List<AccessoryGroup>();
accessoryGroupList.Add(new AccessoryGroup { Id = "test", Description = "This is just test data" });

if(accessoryGroupList.Contains("test"))
{
    // this is true
}

As you can see, using generics and extension methods has saved the day again. There is a lot of generic code in our architecture using the DtoBase class. This is just another example of why generics and extensions are so important.

Our server repositories that feed our REST API use the same DTOs that our portable class library containing our client libraries uses. Because of the shared class library, I can use this new extension method on the server or on the client.

References:

MSDN Extension methods guide
List<T>.Contains() method