Wednesday, 4 December 2013

Goodbye Autofac

Autofac is one of my favorite IoC containers, due to its fluent, easy-to-learn syntax and great performance. However recently it let me down in some occasions and I had to get rid of it in the main project, I am working on. But let me explain it from the beginning.

Since Autofac 3.0, it is compiled against Portable .NET Framework. It is a subset of the usual .NET Framework, which runs on various devices and platforms. Such as Silverlight, mobile etc. The portable framework version number is 2.0.5.0. So far, so good. It worked well in my project with .NET Framework 4.5. But...

1. When we tried to obfuscate Autofac.dll using Dotfuscator version 4.8, it complained that mscorlib.dll version 2.0.5.0 cannot be found. Although it exists in the corresponding directory under C:\Windows\Microsoft.NET\Framework . Travis Illig suggested me to upgrade the Dotfuscator to latest version, which would definitely resolve the problem.

From Dotfuscator v 4.9 release notes:
  • Using String Encryption on Portable Class Libraries will no longer cause Windows Store apps to fail certification.
http://www.preemptive.com/support/dotfuscator-support/dotfuscator-pro-change-log/464

Unfortunately, upgrading Dotfuscator means purchasing a new license, which is pretty expensive. We managed to overcome this problem by putting mscorlib.dll v2.0.5.0 in one of the internal directories. Dotfuscator scans directories and managed to find it successfully.

2. The second problem appeared when we started testing the product on clean machines. We get the following exception, despite the fact that Portable Framework exists on the machine:

Could not load file or assembly 'System.Core, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e, Retargetable=Yes' or one of its dependencies. 

It happens as a result of Microsoft Known Bug KB2468871. It was fixed by the Redmond folks, but the relevant update is not installed on the machine.

So it means, that in order to use Autofac we have to required from our customers to install Windows Updates. Sometimes it might cause issues with corporate customers, that have strict policy regarding machine updates. It was decided that we'll stop using Autofac in this major project and will switch to something less "sensitive".

Nevertheless, we still use Autofac in many other internal projects. So it is not a real "Goodbye"




Wednesday, 13 November 2013

Opt in and opt out using Autofac IoC container

I am a big fan of dependency injection and inversion of control. I strive to use these techniques in almost every project I am involved with. Usually when I develop the project from the ground, the whole design is ready for automatic types scanning and auto wiring. So it is very easy to wire them up using a short piece of code. All the examples in this post will be using Autofac - the addictive IoC container.
 
public IContainer Initialize()
{
    var builder = new ContainerBuilder();
    builder.RegisterAssemblyTypes(GetType().Assembly).AsImplementedInterfaces();
    return builder.Build();
}

But sometimes, I need to prevent some classes from being registered, for example, the instance need to be created in run time with specific context parameters. In this case I use the opt-out, i.e. register all the types except those having a custom attribute:
 
[AttributeUsage(AttributeTargets.Class)]
public class DontRegisterInContainerAttribute : Attribute
{

}

public IContainer Initialize()
{
    var builder = new ContainerBuilder();
    builder.RegisterAssemblyTypes(GetType().Assembly)
        .Where(t => !t.HasAttribute<DontRegisterInContainerAttribute>())
        .AsImplementedInterfaces();
    return builder.Build();
}
In order to use the attribute in this syntax, I am using an extension method:
 
public static class TypeExtensions
{
    public static bool HasAttribute<T>(this Type @this)
    {
        return @this.GetCustomAttributes(typeof (T), false).Any();
    }
}

In some projects, when I am modifying existing code, which is not "IoC-ready", I need to register only a few classes. Hopefully their number will increase in the future. But currently what I am actually want is to type the container: register only these classes, without actually listing them or assume they reside in some namespace or have something in their name. In such cases I use the opposite:
 
public IContainer Initialize()
{
    var builder = new ContainerBuilder();
    builder.RegisterAssemblyTypes(GetType().Assembly)
        .Where(t => t.HasAttribute<RegisterInContainerAttribute>())
        .AsImplementedInterfaces();
    return builder.Build();
}

With the corresponding custom attribute:
 
[AttributeUsage(AttributeTargets.Class)]
public class RegisterInContainerAttribute : Attribute
{
         
}

Using this method of registering only types marked with the attribute also makes the code clearer to co-workers, who might look up for usages of the attribute and find out what classes are registered in the container. In case they are not familiar with Agent Mulder Resharper plugin.


Thursday, 24 October 2013

BizArk documentation on Console application

It seems that the best documentation is "single page" with code snippets. Projects with such kind of documentation are easy to understand and to use. I've just added such documentation to BizArk project. 



Tuesday, 17 September 2013

BizArk::Command-line parsing library

Some time ago I needed a simple command line parsing library. After some research I came to BizArk ToolKit by Brian Brewder. Since then I became addicted to this library, contributed a few features of my own, fixed a few bugs. Now I am proud to tell that its recent release version Bizark.Core 2.0.3 is available on nuget. Please don't get confused with the BizArk toolkit of older versions. Here is a sample usage:
 
    public enum ConsoleMode
    {
        Copy,
        Move
    }

    public class SimpleCommandLineArgs : CmdLineObject
    {
        [CmdLineArg]
        public ConsoleMode Mode { get; set; }

        [CmdLineArg]
        public string Path { get; set; }
    }

    public static class Program
    {
        private static void Main(string[] args)
        {
            ConsoleApplication.RunProgram<SimpleCommandLineArgs>(Start);
        }

        private static void Start(SimpleCommandLineArgs args)
        {
            // Your code goes here
        }
    }
It will parse the following command-line arguments and create an instance of SimpleCommandLineArgs:
 
C:> YouConsole.exe /Mode Move /Path C:\ 
Now available on nuget.org

PM> Install-Package BizArk.Core

For more info visit project site on CodePlex: BizArk

Tuesday, 27 August 2013

Resharper's extract interface moves class property attributes to the interface

When I use ReSharper's magnificent feature of extract interface (Refactor -> Extract Interface), I have mixed feelings. On one hand I am happy that it saved me a lot of dirty work of manual cop-pasting the attributes, methods etc. On the other hand I am frustrated why class's attributes are copied to the interface. What the interface has to do with WCF attribute DataContract or Data Annotation attributes? I would expect ReSharper at least has an option whether to extract with or without the attributes. Apparently there is an open issue on TeamCity youTrack. The issue was open 7 (seven!!!) years ago and has only 3 votes (including myself).
Up vote for the issue: