Showing posts with label Inversion of Control. Show all posts
Showing posts with label Inversion of Control. Show all posts

Monday, October 31, 2016

IOC Container for Tact.NET

Autofac now supports .NET Core, but other IOC frameworks such as Ninject and Unity have yet to port over. While I was looking into IOC frameworks for .NET Core, I had a bad idea...I, for fun, wrote my own Container in Tact.NET!

So, why did I do this? Honestly, it was just a fun academic exercise! I do think that this is a pretty good container, and I intend to use it in some of my personal projects. Would I recommend that YOU use this? Probably not yet, but I would invite you take a look and offer feedback!

Container Design

I have broken the container into two interfaces: IContainer for registration, and IResolver for consumption. There is a abstract class, ContainerBase, that can be inherited to easily create a container that matches other frameworks; for example, I intend to create a IDependencyResolver for ASP.NET.

You may notice that the IContainer does not have any lifetime management methods, that is because ALL of them are implemented as extension methods...

Registrations

To create a new lifetime manager you have to implement the IRegistration interface. There are already implementations for quite a few:

Resolution Handlers

The last part of the container is the IResolutionHandler interface. These resolution handlers are used when an exact registration match is not found during dependency resolution. For example, the EnumerableResolutionHandler will use ResolveAll to get a collection of whatever type is being requested. Another very different example, the ThrowOnFailResolutionHandler will cause an exception to be thrown when no match can be found.

I think that is a pretty good start, but I am hoping that this will continue to grow with time.

Enjoy,
Tom

Thursday, August 27, 2015

IEnumerable Unity Injection

A few years ago I blogged about how to add Lazy Unity Injection, and then a year after that Unity 3 added that feature. Recently I had to dust off this old code to do something similar...

I wanted to use Unity to inject a collection of registered types into one of my services. To do this directly from the container you would use named registrations and ResolveAll. However if you just try to resolve an IEnumerable of a type in a constructor, then Unity will just try to use Resolve and thus throw an InvalidOperationException.

We can easily "fix" this by registering an extension with our container.

Extension

public class EnumerableContainerExtension : UnityContainerExtension
{
 protected override void Initialize()
 {
 Context.Policies.Set<IBuildPlanPolicy>(
 new EnumerableBuildPlanPolicy(),
 typeof(IEnumerable<>));
 }
 
 private class EnumerableBuildPlanPolicy : IBuildPlanPolicy
 {
 public void BuildUp(IBuilderContext context)
 {
 if (context.Existing != null)
 return;
 
 var container = context.NewBuildUp<IUnityContainer>();
 var typeToBuild = context.BuildKey.Type.GetGenericArguments()[0];
 
 context.Existing = container.ResolveAll(typeToBuild);
 
 DynamicMethodConstructorStrategy.SetPerBuildSingleton(context);
 }
 }
}

Sunday, August 31, 2014

Three steps to wire up your IOC container.

How can you dynamically and flexibly wire up your inversion of control container? Here are three easy steps to consider:

  1. Reflection
  2. Explicit
  3. Configuration

First, use reflection to help wire up your boiler plate or dynamic dependencies. Second, explicitly register and customize any additional dependencies that your application needs Third, use configuration last to dynamically override any of your previous settings, allowing you to make changes to your application in a live environment without having to rebuild or deploy.

Sample Code

Microsoft's Unity offers a last in win container, so if you follow the steps above in order you will have a very flexible configuration for your container!

Sunday, February 2, 2014

Understanding Unity Named Registration and ResolveAll

I have a love hate relationship with Microsoft Unity, the dependency injection container.

Unity is a very powerful tool, it is an extensible industrial strength container that comes equipped with a ton of features right out of box. However my big beef with it is how those features are not always discoverable, and often they are less than intuitive.

For example, let's talk about named registration. You can register a type from the container with or without a name. This means you can then ask the container to Resolve just the type itself, getting back the unnamed registration, or you can ask the container to Resolve that type for a particular name. That is great, it is a feature required to register multiple implementations of the same interface.

The ResolveAll method, however, is only for use with named registrations.

There is no way to resolve a collection of both named and unnamed registrations. That is not a bad thing in and of iteself, but it does mean that if you want to register a "default" type you will need to register it twice. (For more help with that see my previous blog post: Understanding Unity Lifetime Managers)

Equally interesting is how ResolveAll returns you an IEnumerable by reference.

This means that that enumerable you get back will dynamically change with registrations being made against the container. This might sound neat, but it raises a few big questions...

Is it thread safe? Nope!
Is that documented? Nope!

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:

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

Sunday, October 20, 2013

Unit Testing and Dependency Injection, with xUnit InlineData and Unity

Inversion of control is great because it makes your code more testable; but you usually still have to write tests for each implementation of your interfaces. So what if your unit testing framework could just work directly with your container to make testing even easier? Well, xUnit can!

Below we define a custom data source for our xUnit theories by extending the InlineDataAttribute. This allows our data driven unit tests to resolve types via a container, and then inject those resolved objects straight into our unit tests.

Bottom line: This allows us to test more with less code!

The rest of post is very code heavy, so I strongly recommend that you start out by taking a look at sections 1 and 2 to get an idea of what we are trying to accomplish. :)

  1. Example Interfaces and Classes
  2. Example Unit Tests
  3. IocInlineDataResolver
  4. UnityInlineDataAttribute
Subscribe to: Posts (Atom)

AltStyle によって変換されたページ (->オリジナル) /