You don't always need an IOC library

The principle of YAGNI should always apply, and I was recently reminded of that when I had to build a small application to give to a user for a small one off task. We’re talking a single screen application with a single button on it. Idiot proof.

So, File > New > Winforms application - doesn’t have to be anything fancy. Then I caught myself: My first instinct was to add StructureMap to it.

I thought to myself that it’s only going to have a few classes, I mean just because it’s a small winforms app doesn’t mean I’m going to shit up the code behind with business logic and data access, so why bother with the overhead of adding a IOC library?

It doesn’t mean I don’t have to use dependency injection. Mark Seemann calls this “Poor Man’s DI”.

    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var service = new Service(new Database(), new Other());
            Application.Run(new Main(service));
        }
    }

It’s short and sweet, and there is no IOC container configuration to worry about. Because I don’t need to.

What about when….

Requirements change. “Can it just do this as well…?” More dependencies required, perhaps another form, maybe another service or two. I think I’d see how far I could push Poor Man’s DI before I brought in a proper IOC container to help manage things.

Configuring SignalR in StructureMap

Configuring SignalR in ASP.NET MVC, using StructureMap as the IoC container is fairly straightforward, but not without some subtleties that caught me out.

For the purposes of this post, I’m going to assume that you are familiar with both SignalR and StructureMap, and that you know how to configure them in an ASP.NET MVC application. I will also assume that through some google-fu you have seen the Dependency Injection in SignalR guidance, and have worked through it and got to the “Using IoC Containers in SignalR” section.

I would assume, although I’ve not tested it, that much of this could also be applied to a self-hosted SignalR server.

Library versions used

This post is based on:

  • Asp.Net MVC 5.2.3
  • SignalR 2.2.0
  • StructureMap 3.1.5.154
  • StructureMap.MVC5 3.1.1.134

Follow the guidance up to the section on using Ninject, at which point we now want to configure StructureMap.

Replace the SignalR Dependency Resolver

The implementation is nearly identical, with some obvious StructureMap specific differences:

public class StructureMapSignalRDependencyResolver : DefaultDependencyResolver
{
    private readonly IContainer _container;
    
    public StructureMapSignalRDependencyResolver(IContainer container)
    {
   	    _container = container;
    }
    
    public override object GetService(Type serviceType)
    {
   	    return _container.TryGetInstance(serviceType) ?? base.GetService(serviceType);
    }
    
    public override IEnumerable<object> GetServices(Type serviceType)
    {
   	    var objects = _container.GetAllInstances(serviceType).Cast<object>();
   	    return objects.Concat(base.GetServices(serviceType));
    }
}

The behaviour is fairly similar. TryGetInstance will attempt to resolve the type, and if it doesn’t know about it, will return null, in which case we call the base resolver, which does.

Register this with StructureMap:

For<IDependencyResolver>().Singleton().Use<StructureMapSignalRDependencyResolver>();

In your Startup, where you configure SignalR, we need to use this new resolver implementation:

var resolver = DependencyResolver.Current.GetService<Microsoft.AspNet.SignalR.IDependencyResolver>();

var hubConfiguration = new HubConfiguration
{
    Resolver = resolver

/* other options as required */
};

Here, we are using the MVC DependencyResolver, which has already been replaced by StructureMap thanks to StructureMap.MVC5, to resolve an instance of the SignalR dependency resolver we’ve registered, which we then tell SignalR to use with a hub configuration object.

Now we just need to configure the StructureMap registry, and teach it how to resolve IHubConnectionContext<dynamic>:

For<IConnectionManager>().Use<ConnectionManager>();
For<IStockTicker>()
    .Singleton()
    .Use<StockTicker>()
    .Ctor<IHubConnectionContext<dynamic>>()
    .Is(ctx => ctx.GetInstance<IDependencyResolver>()
        .Resolve<IConnectionManager>()
        .GetHubContext<StockTickerHub>().Clients);

As in the guidance, we want the StockTicker instance to be a singleton, and we have specify how to resolve the IHubConnectionContext<dynamic> which the StockTicker requires. In the Is, I’m using the context to resolve the default SignalR connection manager we’ve registered. This isn’t in the guidance, but I couldn’t get it work without doing this.

If anyone has comments/improvements on this, I’d love to hear them.

MSBuild Code Analysis (on a build server)

It is possible to setup your build server to run code analysis on your solution/projects, without having to install VS on your build server.

The answer is here: http://stackoverflow.com/a/21731245/3181

I’m not going to reproduce the code here, there is no point. This post is just a reminder to myself as to where I found the solution to this.

Gitlab and Active Directory

Gitlab is an open source ‘clone’ of Github, although I don’t think it’s much of a clone anymore, to be fair. The Enterprise edition has full Active Directory support, and the Community edition does not.

The integration with Active Directory is of great benefit. To get the most out of it, I think that you would need to upgrade to the Enterprise edition, as it adds a number of additonal integrations which look to be really usefull for larger organisations with multiple projects and development teams.

It is possible to configure the Community edition to integrate with Active Directory, to the extent that you can restrict exactly who is allowed to login in. You have to manually configure the users permissions on groups/projects though. In the Enterprise edition, the tighter integration means that you can match up Active Directory groups with groups in Gitlab, and control access both to the server, and groups/projects, all through Active Directory.

Here is the ldap section from my gitlab.yml (please be aware, I’m no Active Directory expert):

ldap:
enabled: true
  servers:
    main:
      label: 'domain'
      host: 'ad.example.com'
      port: 389 
      uid: 'sAMAccountName'
      method: 'plain' 
      bind_dn: 'CN=Git Lab,OU=AB,OU=example,DC=example,DC=com'
      password: 'secret'
      allow_username_or_email_login: true
      active_directory: true
      base: 'OU=example,DC=example,DC=com'
      user_filter: '(memberOf=cn=devs,ou=groups,dc=example,dc=com)'

The bind_dn is for a user called ‘Git Lab’, and you must suppoly the password. This user was expressly setup just for this, but you can use any user. The base is the level of Active Directory that Gitlab searches for users from. Finally, the user_filter states that users must members of devs in order to be able to login.

ASP.Net Bootstrap 3 form control width

Having just been stumped on this for longer than I care to admit, and only finding the answer to my problem buried in a comment on StackOverflow, I’m posting it here for my own future reference:

Q: Using ASP.Net MVC with Bootstrap 3, why won’t my <input> stretch to the full width of a <div class="form-group">, even though I am putting form-control on the css class?

A: Because Microsoft override input, select and textarea to have max-width: 280px in the default Site.css which is added to new projects. Removing this will allow the 100% width from form-control.

Fluent NPoco mappings with StructureMap

I like using NPoco, it’s a really nice library that allows you stop having to write raw ADO.NET. Recently I just switched one of my projects at work to use the Fluent Mapping features, essentially so that my POCO’s do not need to have the mapping attributes in them.

I started wth the example on the NPoco wiki of creating a database factory, and adding the mapping class to the fluent configuration. As the number of mapping classes has grown, this has quickly become unwieldy and a bit of a maintainance issue.

As I already utilise Structuremap in the application, I wanted to configure it to automatically pick up my mapping classes and build the configuration object for me. This is easy to in the registry:

public DefaultRegistry()
{
	Scan(
		scan =>
		{
			scan.TheCallingAssembly();
			scan.WithDefaultConventions();
			scan.With(new ControllerConvention());
			scan.AddAllTypesOf<IMap>();
		});

	For<FluentConfig>().Use(context => FluentMappingConfiguration.Configure(context.GetAllInstances<IMap>().ToArray()));
	For<DatabaseFactory>().Singleton().Use<DatabaseFactory>();
	For<IDatabase>().HttpContextScoped().Use(context => context.GetInstance<DatabaseFactory>().GetDatabase());
}

The mapping classes must inherit from Map<T>, which itself inherits from IMap. Thus we can confidently add all types of IMap in the scan.

Then an instance of FluentConfig must be registered, which can be done with an overload of .Use, from which we get the StructureMap context and pull out all the types of IMap which have been found and pass it to the static .Configure method of the FluentMappingConfiguration, which constructs the instance.

The DatabaseFactory (see below) is then registered, and it accepts a ‘FluentConfig’ instance in its constructor. As per the original example on the NPoco wiki, it is marked as a singleton to ensure that only one instance is created, so that the mappings do not get registered more than once. I don’t know what would happen if the mappings were to be registered more than once, but I assume that it would be a Bad Thing™.

Then, for the NPoco IDatabase instance that we register, we want to always create it using the instance of the DatabaseFactory that has already been registered, which again is accessible using the overload of .Use to get the Structuremap context. It’s marked as .HttpContextScoped(), but I’m honestly not sure if that’s required or not given that I’m using Structuremap.MVC5 nested containers.

For completeness, here is the DatabaseFactory:

public class DatabaseFactory
{
	private static NPoco.DatabaseFactory _internalFactory;

	public DatabaseFactory(FluentConfig fluentConfig)
	{
		Configure(fluentConfig);
	}

	private static void Configure(FluentConfig fluentConfiguration)
	{
		_internalFactory = NPoco.DatabaseFactory.Config(x =>
		{
			x.UsingDatabase(() => new Database("ConnectionString"));
			x.WithFluentConfig(fluentConfiguration);
		});
	}

	public NPoco.Database GetDatabase()
	{
		return _internalFactory.GetDatabase();
	}
}

Learned so much about Vim that I should already know

I’ve been a user of Vim for several years now. I use it as my go-to standard editor. As I primarily write C# code, I obviously use Visual Studio, a lot, and I have the wonderful VsVim extension installed, which provides a lot of the power of Vim, from within Visual Studio.

I thought I was pretty good at using Vim, until the other day when I saw Vim being used in some screencasts and I immediately thought that I suck at using Vim.

It turns out, that I learned enough about using Vim that got me a good increase in productivity, that I basically stopped learning how to use it. My brain must have decided that I learned all I needed to know to get me through my day, and stopped me wanting to learn anymore.

I have now found a great source of screencasts about using Vim, here, which are split into Beginner, Intermediate and Advanced. I learned how to do new stuff with Vim that is in the first beginner video.

I wish that I had found these videos several years ago when I was first starting out with Vim, as watching them then would probably have saved me a lot of time over the last several years.

About those view locator conventions

As I mentioned in a previous post, I do not like some of the default PRISM view location conventions.

As a refresher, these are:

  • View models to be located in a folder called ViewModel, named MyAwesomeViewModel
  • Views to be located in a folder called Views, named MyAwesome

It’s the view naming that I don’t like: In my world (which is based on Caliburn.Micro and ReactiveUI), views should be named MyAwesomeView. This is a simple distinction, but an important one for me because I automatically expect view names to end in View.

Fortunately in PRISM 5, this is easy to change:

ViewModelLocationProvider.SetDefaultViewTypeToViewModelTypeResolver(viewType =>
{
    var viewName = viewType.FullName;
    var viewAssemblyName = viewType.GetTypeInfo().Assembly.FullName;
    var viewModelName = string.Format(CultureInfo.InvariantCulture, " {0}Model, {1} ", viewName.Replace("Views", "ViewModels"), viewAssemblyName);
    return Type.GetType(viewModelName);
});

We get the full name of the view, and the full name of the assembly, and then replace “Views” for the “ViewModels” folder, and add “Model” to the end. I would call this somewhere in your applications startup, such as in the bootstrapper Run.

Autowiring

Something else that you can do in PRISM 5, is autowire the view model and view such that the DataContext of the view is automatically populated.

ViewModelLocationProvider.SetDefaultViewModelFactory(type => Container.GetInstance(type));

I’m using StructureMap here (of which I am a big fan), but you should be able to get to work with your favourite IoC library.

This though, means that you have to tell StructureMap about all your views in order for it to be able to resolve them. That’s too much messing about remembering having to update a Registry everytime I add a view. StructureMap can solve that for us no problem:

public class ViewRegistrationConvention : IRegistrationConvention
{
    public void Process(Type type, Registry registry)
    {
        if (!type.Name.EndsWith("View") || ! type.IsConcrete()) return ;

        registry.For(typeof(object)).Use(type).Named(type.Name);
    }
}

Here we say that if the name of the type being resolved ends with “View”, and it is a concrete type (i.e. not an abstract class or interface), then add it to the registry. The trick with PRISM is that it is asking to resolve an object with a specific name, it doesn’t try to resolve the type of the view, so adding something to the registry as For<MyAwesomeView>().Use<MyAwesomeView>() won’t work, you have to use For(typeof(object)) and make it a named instance, using the name of the type.

And then just register the convention when you configure the container:

Container.Configure(configure =>
{
    configure.Scan(scan =>
    {
        ...
        scan.Convention<ViewRegistrationConvention>();
    });
});

Then from the region manager, you can RequestNavigate("AwesomeRegion", new Uri(typeof(MyAwesomeView))), or use the extension method in my previous post.

A useful PRISM extension method

I’m doing some work with Microsoft Prism at the moment, and once again I’ve gotten annoyed that RequestNavigate doesn’t have a generic overload.

Naturally I had to write it, again:


public static class RegionManagerExtensions
{
    public void RequestNavigate(this IRegionManager regionManager, string regionName)
    {
        regionManager.RequestNavigate(regionName, new Uri(typeof(TView), UriKind.Relative).Name));
    }
}


the ```new Uri(typeof(TView)...)``` works because of the view locator conventions I've implemented.

ReactiveUI - Hello, World!

ReactiveUI is an MVVM framework. I’m going to mess around with it and see if I can make it do something useful, and maybe get shouted at for Doing It Wrong™

A journey starts with a small step, and this journey will, I hope, take me, and you, but mostly me I hope, toward a greater understanding of writing applications with ReactiveUI.

I’m most interested in WPF applications, but I think at least some of what we’re going to get into applies to IOS/Android and WP8 - ReactiveUI is cross-platform by nature, and that is one of the things that makes writing applications with it fairly attractive.

First things first

  1. Create a new WPF application.
  2. Install-Package reactiveui -Pre (Currently 5.99.6)

What our app is going to do, is