Over the Christmas break I found myself with a bit of free time to play with Nancy.  For a long time I’ve fancied writing a link shortener, I even bought the domain vfy.be to serve shortened links from.  I originally had grand plans, it was going to be a social link shortener where links “trusted”/visited by your friends took you straight to them, otherwise you hit a landing page with the amount of hits, the real url and what Google thinks about it or I was going to iframe the page in with a toolbar.  Anyway, twitter got in the link shortening business and I got another idea and decided to move on.  But still how they worked intrigued me.

So I wrote one for fun using C#, mono 2.10 and Nancy.  When looking at the Nancy docs, it is slightly lacking in how to host on Linux so I thought I’d do my bit by writing a quick overview.

Options

There is a couple of options when hosting on Linux, one is to create your Nancy project as a mono ASP.NET project then serve it using xsp (the mono ASP.NET server) and proxying to it or using FastCGI.  This is fairly well documented at the mono site and writing a Nancy app using ASP.NET for hosting is also well documented.  However, I wanted to take a different approach to try and host it in the minimum amount of RAM on an LEB (LowEndBox), because I have a 256MB Xen Debian VPS just sat around doing nothing.

So to minimise RAM I went for self hosting, using pretty much the stock sample with a slight mod (see below). When self hosting the Nancy app will listen on the loopback address at a specified port so we are going to use Nginx to serve static content and forward all requests to our mono process and use Supervisord to monitor the process.

Pull it all together

For this you’ll need the following installed on the Linux machine:

The first we’re going to do is configure Supervisord.  Supervisord is a process monitoring application that can run any normal process as a daemon and automatically restart it if it crashes.  I first came across this when working with Python sites to keep FastCGI processes running.   The configuration should look something like:

The important bits are:

  • command – this specifies the command believe it or not,
  • user – by default supervisord runs all processes as root, this is bad for webapps.
  • directory – this sets the working directory, so if you’re app needs anything off disc this needs to be correct.

As I said above I needed to make a tweak to the sample self hosting project.  The sample uses Console.ReadLine() to stop the process from exiting, but under Mono when running as a daemon this returns EOF and causes the application to close.  So I updated it to sleep (shamelessly stolen from xsp source :) ):

Moving on we need to configure Nginx. The strength of Nginx is serving up static content quickly so we’re going to intercept all requests for static files and then forward the rest to our Nancy app. The configuration below defines an ‘upstream’ which is typically used for load balancing we can use it here for just forwarding requests. Also note we are intercepting and serving requests for /Content using Nginx.  At debug time the default conventions in Nancy will serve this up correctly so we get best of both worlds :)

How well does it do on our LEB?

Impressively, idle the combination of Debian Sid, Supervisord, Nginx and the Mono process takes up just 37MB of RAM, but the most important question is can it handle load?  ***Beware completely unscientific results below :) ***

Lets take a look at hitting one of the json API methods* using ApacheBench (that is bundled with OSX :) ):

  • 1000 continuos requests with a max of 10 concurrent connections peaks memory at 53MB
  • 1000 continuos requests with a max of 25 concurrent connections peaks memory at 54MB but 18 out of the 1000 failed with connection reset by peer, which is more the box failing than the app
  • 1000 continuos requests with a max of 50 concurrent connections peaks memory at 55MB but my own boardband gave up after 700 connection, clearly not enough upspeed :)
*It’s important to note that this app is one static html page with ajax queries back to a JSON api served by Nancy

Wrapping Up

I hope someone finds my configuration snippets useful and it is worth noting that my LEB (£2.20 a month for 256MB Xen) failed before the my app did, so I find this very encouraging for it’s performance under Mono and Linux.

Source for the link shortener and conf files can be found at https://github.com/Dotnetwill/vfy.be
The shortener running on Mono http://vfy.be

, , , ,

I love code reviews, I really do.  I like having my code looked at and receiving feedback and I like to look at other peoples to see differing styles, techniques and library functions I might not be aware of.  But I always struggle to find the best way to do code reviews.  So I want to take a look what you need to perform a code review and how to review the code.

Prerequisites

Some people are just really bad at writing bug reports and work items (I’m looking at you developers) but this is the most important thing you need when reviewing the code, apart from the code.  You need to able to read the original bug report and understand it then see the developers analysis and proposed solution so you know what you’re looking at when you review it.  Without this it becomes extremely difficult and time consuming to redo all the work that has already been done to identify the problem.

Leave your style at the door, at the office we don’t have one complete standard, we have general rules about casing, and what not, but there isn’t one enforced style. I find it really helps to tune out to subtle differences in style, so long as it’s readable it really doesn’t matter.

The Review

I like to start with some simple things:

  • Run it – Check that the bug has been fixed or the work item has been implemented.  Take it through some basic sanity checks with the debugger attached, if possible, with stop on EVERYTHING enabled and see what it does.  No point in reviewing code that doesn’t do what it’s meant to do.  If it has unit tests run them, step through a few with the debugger to get a feel for how it’s meant to work.
  • Check for build warnings – Ok that might sound petty, but I generally think warning should be treated as errors.
  • Is it readable – This is the most important, if you can’t read it how do you expect it to be maintained?  Or you don’t understand the change enough to give it a good review.

By this point we have checked that the code is working and that we understand it. Now for the hard part, looking at it.  At the business end of a code review I generally look for the following things (C# specific):

  • Delegate Registration – Whenever I see a delegate being registered I always look for a corresponding deregistration.
  • Resources Being Release – If a resource (file, db, etc) is opened, make sure it is released again at some point.
  • General Exception Handling – I always look for things I know, from experience, are likely to throw and see if there is exception handling around it.  Whenever there is a catch block, I look at how it is dealt with and what is caught.
  • TryParse v Parse – Parsing values is always error prone, and we do a lot of it in our codebase, so I’m a stickler for correct exception handling or using the TryParse methods.
  • Null Checking (or Use of a Null Pattern) – Defensive coding should be our bread and butter so this should always be present
  • General WTF-ery – Anything that makes me utter those three little letters.

I think this covers most points, it’s not an exhaustive list but I think code reviews are more about checking maintainability than quality, although it definitely helps with it.

When giving feedback I like to try and speak to the person first and ask them about it, remember one person’s WTF is another person’s complex issue. Alternatively, I jot a few points down in an email.  I don’t see the need for a separate code review tool when other forms of communication are effective and flexible.  Finally, always be constructive, it’s hard to get people to listen if your just being negative so state your reasons clearly, ask them why it’s like that and always resist the urge to say “W.T.F is going on here dude”.

I started off this blog post with a view to clarifying in my own mind how best to do code reviews, but looking back and rereading my approach I feel there is room for improvement.  So I ask you my dear readers:  What do you think makes a good code review?

, ,

“Have you considered working in another area in software, you don’t seem to have the right personality type to be a developer”…Said the head of development sat across the table from me.  I sat, head down, a mere 18 months out of university having just delivered my first major product release being told that I was no good at what I do.  I love programming, it has been my hobby since I got my first computer and it was the only job I’d ever wanted to do.

As I’m sure you can imagine, I was devastated but not entirely shocked.  You see I used to rush through a task or bug to get to the next one or get distracted by something shiny.  The best way I can describe it, is as a Magpie effect and, as I was being made aware of at that moment in time, developers are expected to be completer finishers and meticulous to a fault.

I was aware of TDD and I had tried to write some tests but I really struggled with how to make code testable and good unit tests that didn’t just test “stuff”.  But this time I was determined to learn more and put it in to practice, it seemed like the perfect answer.

Present Day…

That was nearly two years ago now, I’ve grown massively as a developer since that day and TDD has been my gateway drug to professionalism. When I started off with TDD I thought it was about testing but when I look back at my journey thus far, it’s about anything but.

One of my biggest problems was rushing, I was always desperate to finish and I missed things or didn’t think them through properly.  The first thing that writing unit tests helped me to do was slow down and break problems into much smaller chunks.  Just taking a few minutes to consider how best to write the test normally exposes any concerns that need to be separated, edge cases and how the class or function will be interacted with.  If I’m ever struggling to make a test pass, write a test or if I can’t make all the tests pass, it normally means I need to go back and look at the tests to see if I’m trying to solve too much in one go or if it has contradictory responsibilities.

The tests provide excellent documentation that is hard to argue with and stays in step with the code.  This is key because it gives me an insight in to what I was thinking and how I intended on it being consumed.  It’s, also, the closest to an interactive interrupter for C# I have used, which is great for rapidly checking assumptions and questioning your own code.

Overall it has taught me so much about architecture, design, good practice and maintainability of code.  One conclusion I have to come is that unit testing has a very low regression value.  At this moment in time I rarely, if ever, find bugs using unit tests.  Yes they help to identify failure points but it’s not very often I find regressions using them.  All they have done is shifted the pain point from if the logic works to if it all works together.  My next challenge is step deeper into the world of the integration testing.

,

I’ve read many books and blogs that advocate only having one assert in a unit test and lots of people take that to mean literally assert statement.  I’ve always disagreed with taking it literally, I’ve always thought of it as one logical assert, as in you assert one concept at a time which could lead to multiple assert statements.

The main arguments against having more than one assert statement seems to be it’s not as readable and it’s sometimes difficult to understand what is failing because of it.  My normal response is to create my own asserts that accurately describe what the multiple asserts do and hide the real asserts in there.  For example:

 
   1: public void AssertIsValidClone(Customer oldCustomer, Customer actualCustomer)

   2: {

   3:     Assert.AreNotSame(oldCustomer, actualCustomer);

   4:     StringAssert.AreEqual(oldCustomer.Name, actualCustomer.Name);

   5:     StringAssert.AreEqual(oldCustomer.Address, actualCustomer.Address);

   6: }

   7:  

   8: [Test]

   9: public void Clone_ValidCustomer_ValuesAreTheSameReferenceIsDifferent()

  10: {

  11:     //Some setup

  12:  

  13:     var result = aCustomer.Clone();

  14:     

  15:     AssertIsValidClone(aCustomer, result);

  16:     

  17: }

 

Ok so this is a very contrived example but we can clearly see what the intent of the assert is rather than having several making it harder to understand.  But what this doesn’t do is address the second concern. IE anyone of those three asserts could fail, so we fix it then the next fails, etc.

Enter an nUnit plug in called OAPT, this allows you to have multi asserts that generate multi unit tests in the runner so you can see exactly what is failing.  I won’t warble on too much about the details because it’s all in the link But let’s just rewrite our unit test:

 

   1: [Test, ForEachAssert]

   2: public void Clone_ValidCustomer_CloneIsNewItemWithValidData()

   3: {

   4:     //some setup

   5:     

   6:     var newCustomer = originalCustomer.Clone();

   7:  

   8:     AssertOne.From(

   9:         () => Assert.AreNotSame(originalCustomer, newCustomer)

  10:         () => StringAssert.AreEqual(originalCustomer.Name, newCustomer.Name)

  11:         () => StringAssert.AreEqual(originalCustomer.Address, newCustomer.Address));

  12: }

 

Much more concise and it will run as three separate tests.  I still do have an issue with it though, each test uses the test name with an appended number. It would be nice if you could pass in some text for it to append.  But then again it is open source so maybe I could add that feature myself :)

, , ,

Today I have pushed new binaries to CodePlex for DirLinker.  This new release brings support for folder links in Windows XP/2003.  It is not able to create file links, this is because of the limitations in reparse points in earlier versions of Windows.

This is something I didn’t think I would do but after releasing Dirlinker 2 on Codeplex, a ticket was raised in the bug tracker because it was failing on XP and I was chatting to a friend on IM about it who basically said “Well why doesn’t it?”.  The main reason was because the API call for creating symbolic links is only available in Vista and later.  XP does have an equivalent but the behaviour of the links they create is subtly different.  In XP they are Reparse Points where as in Vista+ they are hard links (similar to *nix), I will go in to the difference in a future post.

It turns out that with a little help from a CodeProject article, it took less than an hour to put in and test, so it made it in.  I am definitely parking this to new features now.  Only bug fixes will be added from now on.

, , , , , ,

After literally months of procrastination Directory Linker 2 is finally in state that I’m not too ashamed of.  So today I have posted up new binaries on Codeplex.

What’s New?

  • Undo Support  If the process of moving and deleting a folder before creating a link at the same location failed, you could end up with some files in the new location, some in old and two partial directory structures.  If this happens now DirLinker will offer to put the original folder back how it was.

    If you’re using the just delete option and it fails, undo can not undelete any files but it will put back any folders it deleted.

  • File Links – It can now create symbolic links for files as well as directories.  You don’t have to do anything different, just select a file in the link location or the link to field.  There has been a small change to the UI to allow you to browse for files aswell as folders.

    In a future post I’m going to talk about the difference between symbolic links and shortcuts.  But for now the important difference is the application opening file doesn’t know the file is only a link when using symbolic links.

  • Progress Window Changes – The progress window has been slightly overhaul and now keeps a list of everything it has done.  So if it does fail or something goes wrong, you can work out exactly what it’s done.

Progress Window

With these features I’m planning on parking Directory Linker development, I will of course fix any bugs that may come up but I can’t see any new features being added.

Enjoy!

PS, If you have no idea what Directory Linker is, this is a good place to start.

, , ,

When I originally released OCInject I omitted one important feature, lifestyle management.  This coupled with the release of a feature full TinyIOC has made me re-evaluate my position on not adding too many features to OCInject.  Release 2 of OCinject brings the following features:

  • Life style management – It’s possible to register types as singletons or instance
  • Func<T> factories – OCInject from day one supported delegate factories, now you can use Func<TContract> instead of typed delegates
  • Simplified Registrations In the previous release of OCInject types are registered using TContract –> TImplemenation to enforce programming to interface.  It’s now possible to register with TContract as the concrete type with one call
  • Largest Resolvable ConstructorIn the previous release of OCInject it simply grabbed the first constructor it found.  It will now select the greediest constructor it can resolve.  It makes the assumption that any known types are resolvable, for performance reasons.
  • Unresolveable CallbackIt is now possible to supply a call back function if the container can’t resolve a type.
  • Child Container SupportOCInject can create child containers that call back to the parent for any unknown types. 

The latest stable version can be downloaded from Codeplex and all stableish development releases can be found at BitBucket.

Future Features

One major feature still missing from OCInject is named registrations.  This is because I personally dislike ‘magic strings’, with this in mind a planned future feature of OCInject is factory delegate registration only.  Also, auto generated factories from interfaces.  More to come on this in a future post.

Life Style Management

By default all types registered with the OCInject container are transient. You can register a type as singleton in two ways.  The first method is to use .AsSingleton() this will cause the object to be created the first time it is requested.  The second method is to use .AlwaysReturnObject(obj), this will return the instance you specified.   When using either method, if the type implements IDisposable it will be disposed when the container is.  Usage example:

ClassFactory container = new ClassFactory();

//Normal Singleton
container.RegisterType<TestClass>()
           .AsSingleton();

//Preconstructed Singleton
AnotherClass instanceOfAClass = new AnotherClass();

container.RegisterType<TestClass>()
         .AlwaysReturnObject(instanceOfAClass);

Func<T> Factories

When resolving constructors if OCInject discovers a Func<T> where T is a registered type, it will pass in a func to create the type.  This uses the standard container resolve, so if T is a singleton you will always get the same instance when the factory is called. Usage example:

class FuncConsumer
{
	public FuncConsumer(Func<TestClass> factory)
	{
	}
}

ClassFactory container = new ClassFactory();

container.RegisterType<FuncConsumer>();
container.RegisterType<TestClass>();

//Successfully created with the ability to create TestClass
FuncConsumer f = container.ManufactureType<FuncConsumer>();

Simplified Registrations

Registrations no longer require the separation of contract and implement so just an implementation can be registered.  Usage example:

ClassFactory container = new ClassFactory();

container.RegisterType<TestClass>();

var t = container.ManufactureType<TestClass>();

Largest Resolvable Constructor

This is quite a complicated area that is worthy of a blog post itself but OCInject’s behaviour has changed.  When creating a type the constructors are ordered so the largest, in terms of parameters, is first.  It then looks at each parameter and to see if it can resolve it, first by checking ‘resolve time args’ (values passed in when the resolve is requested, normally from generated factories) then by seeing if the type is a registered contract within the container.   It does not check if the type can be created just that it knows about it, if it’s registered it assumes it can be created.

The first completely resolvable constructor will be used to construct the type.

Unresolveable Callback

If the container is unable to resolve the type you can now register a function that is called before the container throws an exception.  To do this you need register a Func<Object, Type> with the CallToResolve propriety.  Returning null will cause the container to throw an exception.  Usage example:

ClassFactory container = new ClassFactory();

container.CallToResolve = (type) => { return new TestClass(); };

ITestClass manufacturedType = factory.ManufactureType<ITestClass>();

Child Container Support

Calling CreateChildContainer() will return a new ClassFactory object with no registrations but a link back to the parent.  If a type is not known to the child it will ask the parent to fulfil the request.  Any registrations with the child will not effect the parent and singletons registered with the child will be disposed when it is. Usage example:

ClassFactory container = new ClassFactory();
ClassFactory child = factory.CreateChildContainer();
, ,

In my last post I talked about passing reference types using the ref keyword but it didn’t make a lot of sense.  So I just want to go over it again, hopefully making a bit more sense.

When a method is called in C# a copy of the all parameters are given to the method.  This is fairly obvious with value types because if we change the value of an int, for example, the caller does not get the updated value.

However this is not so clear for reference types.  The called method can update the state of the object it was passed, for example append extra data to a StringBuilder, and the caller’s object will have these updates.  This can lead to confusion about what is really happening, it looks as if the StringBuilder was passed by reference but a copy of the reference to it was taken.  

It maybe subtle semantics under normal use but it becomes key to understanding behaviour when the ref keyword is used.  For value types this means that if we increment an int we are passed, the caller will have the new value too.  For reference types the reference we are passed is actually a reference to the caller’s reference. Meaning if we assign a new reference to it, the caller will get the new reference.

We can demonstrate this with the following code: 

static void Main(string[] args)
{
    StringBuilder sb = new StringBuilder();
    sb.AppendLine("Added by Main");

    AddToSBPassedAsNormal(sb);
    Console.Write(sb.ToString());
    //Output: Added by Main
    //        AddToSBPassedAsNormal

    AddToSBPassedByRef(ref sb);
    Console.Write(sb.ToString());
    //Output: AddToSBPassedByRef

    AddToSBPassedAsNormalNewUsed(sb);
    Console.Write(sb.ToString());
    //Output: AddToSBPassedByRef

    Console.ReadLine();
}

private static void AddToSBPassedAsNormal(StringBuilder sb)
{
    sb.AppendLine("AddToSBPassedAsNormal");
}

private static void AddToSBPassedByRef(ref StringBuilder sb)
{
    sb = new StringBuilder();
    sb.AppendLine("AddToSBPassedByRef");
}

private static void AddToSBPassedAsNormalNewUsed(StringBuilder sb)
{
    sb = new StringBuilder();
    sb.AppendLine("AddToSBPassedAsNormalNewUsed");
}

From the code above we can see that the StringBuilder after the first method contains both strings.  But after the method call, where it is passed by ref, the previously entered data has been lost and, finally, using new when not being passing by reference has no effect on Main()’s reference to the StringBuilder.

Before passing a reference type using the ref keyword you must think carefully about the implications of the caller changing the reference.  As it can lead to some esoteric and difficult to track down bugs.

, ,

For the past couple of weeks I’ve been deep in some legacy code.  The code has all kind of hidden charms, while I’m not going to be overly critical because it was written at a time when a .NET 2.0 application was cutting edge.  I uncovered this gem:

public void SomeHighLevelFunction(out String feedback)
{
	StringBuilder mySb = new StringBuilder();

	_WorkerItem1.DoWorkOne(ref mySb);
	_WorkerItem2.DoWorkTwo(ref mySb);
	_WorkerItem3.DoWorkThree(ref mySb);

	feedback = mySb.ToString();
}

Ignoring the void with the out String, why pass the StringBuilder by ref?  This code was written by a migrating C++ programmer; if you’ve worked with C++ at all a little light bulb may have just gone off for you.  It works, even though it might be the very definition of programming by coincidence, so why is this so bad? 

Why So Bad?

When calling a method in C# all parameters are passed by value.  It is a common misconception that reference types are passed by reference when they are infact passed by value.  This backs up the position of the C++ programmer, so what is the difference?

C# and its documentation has no concept of pointers (outside of IntPtr) when they are used extensively under the hood.  When you call a method and pass a reference type you are actually passing a pointer (that lives on the stack) to a memory location on the heap.    The pointer is copied so you can still manipulate the memory but you can’t affect the reference.  For example:

static void Main(string[] args)
{
    StringBuilder sb = new StringBuilder();
    sb.AppendLine("Added by Main");

    AddToSBPassedByRef(ref sb);
    AddToSBPassedAsNormal(sb);

    Console.Write(sb.ToString());

    Console.ReadLine();
}

private static void AddToSBPassedByRef(ref StringBuilder sb)
{
    sb = new StringBuilder();
    sb.AppendLine("Added by AddToSBPassedByRef");
}

private static void AddToSBPassedAsNormal(StringBuilder sb)
{
    sb = new StringBuilder();
    sb.AppendLine("AddToSBPassedAsNormal");
}

 

Has the output of:

Added by AddToSBPassedByRef

This could be confusing to a C++ developer because all classes, in C++, are created on the stack unless you declare a pointer and use new to create them on the heap.  Having said that a simple rule applies to both to C# and C++, if you have to use new it gets created on the heap and everything else is created on the stack.  Anything on the stack, value types or reference types, is copied between method calls.

</rant>

,

**Update** I’ve created a CodePlex project: http://ocinject.codeplex.com

I’ve been learning about Dependency Injection (DI) and Inversion of Control, one of the ways I’ve done this is by creating my own mini DI framework for use in DirLinker.  I’ve, also, looked at the big name frameworks and read lots along the way but I want to give something back to the community that has taught me so much.  So I’m releasing my tiny DI framework used in DirLinker independently as OCInject.

OK, So Why Is This Different To X

My aim when creating OCInject was to create something that can be used in small projects, single exe utilities or one off apps, where you want the advantages of a DI container but without the overhead of Castle, Autofac, et al.  So consider this DI lite, you simply take the two files, IClassFactory.cs and ClassFactory.cs, and drop them in to your project.  That’s it, done, no external dependency and no XML config file. What do you get?

Features:

  • A DI Container with fluent like configuration
  • Ability to resolve constructor parameters for registered types and passed in constructor arguments
  • Runtime delegate factory generation
  • Pseudo session support via IDisposable.

The feature list is tiny and is very unlikely to grow; well maybe by one, singleton support.  It is not meant to compete with or to replace anything that already exists.

How To Use It

Basic Resolution

As I said above first thing to do is copy IClassFactory.cs and ClassFactory.cs into your project, then fill the container and resolve your type.  For example

    public interface IMyClass
    {    }

    public class MyClass : IMyClass
    {  }

    public class MyApp
    {
        public void Run()
        {
            IClassFactory factory = new ClassFactory();

            factory.RegisterType<IMyClass, MyClass>();

            IMyClass myClass = factory.ManufactureType<IMyClass>();
        }
    }

If the class has dependencies we can inject these just by specifying them as constructor arguments on our class and the container will resolve them if they are registered.  For example

public interface IMyClassWithDepend
{}

public class MyClassWithDepend
{
    public MyClassWithDepend(IMyClass depend)
    { }
}

public class MyApp
{
    public void Run()
    {
        IClassFactory factory = new ClassFactory();

        factory.RegisterType<IMyClassWithDepend, MyClassWithDepend>();
        factory.RegisterType<IMyClass, MyClass>();

        IMyClassWithDepend myClass = factory.ManufactureType<IMyClassWithDepend>();
    }
}

Auto Delegate Factories

For auto generated delegate factories we need to create a delegate that returns the contract type. Then register this with the container using the WithFactory<T> method when registering the type. For example:

public delegate IMyClassCreatedByFactory FactoryMethodName();

public interface IMyClassCreatedByFactory
{ }

public class MyClassCreatedByFactory
{ }

public class FactoryConsumer : IFactoryConsumer
{
    FactoryMethodName _Factory;
    public FactoryConsumer(FactoryMethodName factory)
    { _Factory = factory; }

    public void DoWork()
    {
        IMyClassCreatedByFactory c = _Factory();
    }
}

public class MyApp
{
    public void Run()
    {
        IClassFactory factory = new ClassFactory();

        factory.RegisterType<IFactoryConsumer, FactoryConsumer>();
        factory.RegisterType<IMyClassCreatedByFactory, MyClassCreatedByFactory>()
            .WithFactory<FactoryMethodName>();

        IFactoryConsumer myClass = factory.ManufactureType<IFactoryConsumer>();
		myClass.DoWork();
    }
}

Auto Delegate Factories With Parameters

Delegate factories can take parameters and pass them on to the constructors of objects.  This is still a bit limited because it doesn’t intelligently select the correct constructor, just the first it comes across (maybe a feature for the future :P ).  To use them just add parameters to your delegate declaration and a create a constructor on your implementation type that matches.  You can still have dependencies that are resolved by the container in the constructor, for example:

public delegate IMyClassCreatedByFactory FactoryMethodName(String param1);

public interface IMyClassCreatedByFactory
{ }

public class MyClassCreatedByFactory
{
    public MyClassCreatedByFactory(IMyClass myClass, String param)
    { }
}

public class FactoryConsumer : IFactoryConsumer
{
    FactoryMethodName _Factory;
    public FactoryConsumer(FactoryMethodName factory)
    { _Factory = factory; }

    public void DoWork()
    {
        IMyClassCreatedByFactory c = _Factory("OCInject filling a gap that doesn't exist");
    }
}

public class MyApp
{
    public void Run()
    {
        IClassFactory factory = new ClassFactory();

		factory.RegisterType<IMyClass, MyClass>();
        factory.RegisterType<IFactoryConsumer, FactoryConsumer>();
        factory.RegisterType<IMyClassCreatedByFactory, MyClassCreatedByFactory>()
            .WithFactory<FactoryMethodName>();

        IFactoryConsumer myClass = factory.ManufactureType<IFactoryConsumer>();
        myClass.DoWork();
    }
}

Where to Get it From and Further Examples

You can download it from BitBucket at http://bitbucket.org/humblecoder/ocinject/.  I don’t have any documentation at the moment but you can look at the DirLinker source and the unit tests for OCInject for more examples.

Enjoy and I hope someone finds it useful :)

, , , ,