Skip to content

Instantly share code, notes, and snippets.

@Dkowald
Created November 15, 2011 21:59
Show Gist options
  • Select an option

  • Save Dkowald/1368516 to your computer and use it in GitHub Desktop.

Select an option

Save Dkowald/1368516 to your computer and use it in GitHub Desktop.
SpringDuck - spring factory for Impromptu
using System;
using ImpromptuInterface;
using Spring.Objects.Factory.Config;
namespace derek.kowald.BaseWebApp.Core.Extensions.Spring
{
/// <summary>
/// Custom <a href='http://www.springframework.net/'>spring.net</a>
/// factory for creating an object that implements
/// a specified interface, using a target object (<a href='http://en.wikipedia.org/wiki/Duck_typing'>duck-typing</a>).
/// </summary>
/// <remarks>
/// Leverages Impromptu for the heavy lifting, see
/// <a href="http://code.google.com/p/impromptu-interface/">http://code.google.com/p/impromptu-interface/</a>
/// Usefull for putting an interface onto a non-interface class, as found in many
/// .NET framework classes.
/// </remarks>
/// <example>
/// var raw = new MyObject();
/// var factory = new SpringDuck()
/// {
/// TargetInterface = typeof(IOther),
/// TargetObject = raw
/// };
/// factory.AfterPropertiesSet();
/// IOther wrapped = (IOther)factory.GetObject();
/// </example>
public class SpringDuck : AbstractFactoryObject
{
#region Properties
/// <summary>
/// Gets or sets the target <see cref="System.Type"/> interface.
/// </summary>
public Type TargetInterface { get; set; }
/// <summary>
/// Gets or sets the target object instance to delegate interface calls to.
/// </summary>
public object TargetObject { get; set; }
/// <summary>
/// Gets the factory returns a 'type'. This is defined by <see cref="TargetInterface"/>.
/// </summary>
public override Type ObjectType
{
get { return TargetInterface; }
}
#endregion
#region Impl
/// <summary>
/// Post set-up checks the factory is configured.
/// </summary>
public override void AfterPropertiesSet()
{
if (TargetInterface == null)
{
throw new ArgumentException("The TargetType must be provided.", "TargetType");
}
if (TargetObject == null)
{
throw new ArgumentException("The TargetObject msut be provided.", "TargetObject");
}
if (!TargetInterface.IsInterface)
{
throw new ArgumentException("The TargetType must be an interface.", "TargetType");
}
base.AfterPropertiesSet();
}
/// <summary>
/// Creates a dynamic object with the <see cref="TargetInterface"/>, using
/// <see cref="TargetObject"/> to implement the interface.
/// </summary>
protected override object CreateInstance()
{
return Impromptu.DynamicActLike(TargetObject, TargetInterface);
}
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment