Saturday, January 18, 2014

Sharing Generic Configuration Across Projects

When you work with a team of developers on a large application across multiple projects, everyone is going to need access to unique configuration settings. Often this will give rise to each project having it's own separate configuration services, or worse everyone will just call the static ConfiguationManager directly.

How do you share a single configuration object across projects?

The answer is simple: extension methods! Just create a generic configuration service in your core library, and then have all of your other projects call it via extension methods. This ensures that you only have one testable, injectable, and extensible source for configuration. Additionally it keeps all of your configuration both discoverable and abstracted to their consuming project.

public interface IConfigService
{
    T Get<T>(string key);
    T Get<T>(string key, T defaultValue);
}
 
public static class ConfigServiceExtensions
{
    private const string NotificationsKey = "AreNotificationsEnabled";
    private const bool NotificationsDefault = true;
 
    public static bool AreNotificationsEnabled(this IConfigService config)
    {
        return config.Get(NotificationsKey, NotificationsDefault);
    }
}

Remember, every project can have it's own set of ConfigService extension methods. :)

Saturday, January 11, 2014

Dependency Injection with SignalR and MVC

Thank you to Isaac Abraham for bringing this solution to my attention!

Do not extend DefaultDependencyResolver

How do you practice inversion of control with SignalR? The official SignalR documentation suggests that you extend the DefaultDependencyResolver base class, and then register that as SignalRs dependency resolver.

This however, can have some nasty side effects! In my case, the ConnectionManager.GetHubContext method was not properly resolving my contexts, and thus I was unable to broadcast messages to my hubs clients.

So then, what is a less obtrusive way to inject your dependencies into your hubs?

Instead register an IHubActivator with the DependencyResolver

A simpler solution is just to register a custom HubActivator with the already existing DependencyResolver. This means that instead of completely replacing the SignalR resolver you are instead adding to it.

The HubActivator is only used when trying to resolve a hub; thus the activator can wrap your container of choice and use it to resolve your hub with its dependencies, while leaving the rest of the SignalR pipeline intact.

SignalR Startup with MVC DepenencyResolver

What does this all mean? It means that once you have your dependency injection setup for MVC, you can then create hubs with dependencies using the same container! This MvcHubActivator will use the default System.Web.Mvc.DependencyResolver to resolve its Hubs:

Wednesday, January 8, 2014

Blogging Schedule for 2014

It is amazing to me that I have been blogger for five years now! I am very proud that for the past two years I upheld the standard of writing at least two posts per month, and for the past six months I have doubled that with four posts per month.

Next year I am going to throttle my tech articles back down to three per month, and try to diversify my efforts a bit more...

  • www.TomDuPont.net
    • Three Tech Articles per Month
  • www.QQ-Cast.com
    • Two "Quest" Podcasts per Month
    • *NEW* Two "News" Podcasts per Month
    • One Written "QQ Review" per Month
    • *NEW* One Video "Let's QQ" per Month

Obviously, this is a VERY aggressive content schedule! The videos are something that I used to do professionally, and now I want to get back into them for just for fun. Regardless of everything else, my highest priority will be to maintain the technical articles on this site.

Happy New Year,
Tom

Friday, December 27, 2013

Understanding Unity Lifetime Managers

I absolutely love inversion of control, it is a best practice that I encourage developers to use in every project that they work on. However, like any great tool, dependency injection can cause serious problems if you do not fully understand it; lifetime management in particular.

As a developer you need to be cognisant of how many instances the container is constructing of your classes. You need to know when singleton is going to consume a transient or non thread safe resource. If you are not careful you can leak memory, share unsafe resources, or just make your garbage collector thrash.

Here is a series of examples regarding how to use lifetime managers in my favorite dependency injection container, Microsoft Unity.

  1. ResolveType
  2. Default Lifetime Manager
  3. TransientLifetimeManager
  4. RegisterInstance
  5. ContainerControlledLifetimeManager
  6. ExternallyControlledLifetimeManager
  7. ContainerControlledLifetimeManager with Multiple Keys
  8. RegisterType for Multiple Interfaces
  9. ContainerControlledLifetimeManager with Multiple Interfaces
  10. TransientLifetimeManager with Multiple Interfaces
  11. RegisterInstance Multiple Times
  12. RegisterInstance Multiple Times with External Lifetime Manager

Wednesday, December 18, 2013

Injectable Dataflow Blocks

I really enjoy working with Dataflows, but I always want to resolve my blocks with dependency injection. Thus I have created some abstract wrapper classes around the sealed ActionBlock and TransformBlock classes. This way your can put my logic into the superclass and inject it's dependencies via constructor injection. Additionally, the action method is public, making it even easier to test your code!

Update: I refactored to ditch the constructor parameters in favor of a new abstract BlockOptions.

Sunday, December 15, 2013

Throttling Datafow and the Task Parallel Library

The Task Parallel Library is an amazingly powerful and versatile library. However, knowledge of how dataflow blocks process their data is vital to using them correctly. Trying to link source and target blocks to each other without fully understanding them is like throwing a live grenade into your app domain; at some point it will tear it down!

I recently experienced a bug where linking two blocks together without managing their Bounded Capacity caused them queue actions at an unsustainable rate, and eventually the dataflow literally eat all of the available memory on the server. This could have been easily avoided by throttling the source and target blocks.

How do you throttle your source block based on your target block?

Once linked together, a source block will produce messages as fast as it's target block can consume them. To prevent a source block from being too greedy, you want to restrict the bounded capacity for both it and it's consumer. Even then, you still need to understand that setting a bounded capacity could cause message producers to either block or fail to post.

...I'm sorry, but this subject is very complex, but I think code will explain these details best! Below are a detailed set of tests to take you through all the basic scenarios for throttling a dataflow:

Saturday, December 7, 2013

ConcurrentDictionary.GetOrAdd and Thread Safety

.NET 4.0 added the awesome System.Collections.Concurrent namespace, which includes the very useful ConcurrentDictionary class. While the ConcurrentDictionary is thread safe, it can experience problems with adding values during high concurrency...

ConcurrentDictionary.GetOrAdd may invoke the valueFactory multiple times per key.

This behavior will only happens under high load, and even if the valueFactory does get invoked multiple times the dictionary entry will only ever be set once. Normally this is not much of a problem. However, if you are using this Dictionary to store large or expensive objects (such as unmanaged resources or database connections), then the accidental instantiation of multiple of these could be a real problem for your application.

Don't worry, there is a very simple solution to avoid this problem: just create Lazy wrappers for your expensive objects. That way it will not matter how many times the valueFactory is called, because only one instance of the resource itself will ever actually be accessed and instantiated.

Real Time Web Analytics