This theme is downloaded from wordpress themes website.

Archive for the 'c#' Category

Making Unity work more like the others

I love MS Unity as an IoC container, it has some great features. Though I found it to function incorrectly at two points (it’s not that the path chosen by the Unity team is incorrect, I just want/excpect it to act differently).

The first thing that bothered me was the fact that Unity throws an exception when Resolve<T> is not able to resolve the given type: I’d prefer it to return null instead, hence most containers do that. The second, even more irritating point, was that ResolveAll<T> only returned the named instances/types instead of all registered types. In fact, Unity overwrites the default registration if your register a type multiple times. Eg:

Container.Register<IMyInterFace, MyClass1>();
Container.Register<IMyInterFace, MyClass2>();

would cause the MyClass1 registration to be removed. I’d like the MyClass1 to remain the default registration, and have ResolveAll<IMyInterface>() return both. I’m happy to tell you that it can be done!

When using an IoC container, it’s good practice to access it’s features through a generic wrapper class. For my projects, I use the wrapper from the Kigg source code. If you access the container through a wrapper after you configured your container, it’ll be easy to replace it with a different container in the future.

My wrapper class looks like this:

public class UnityDependencyResolver : IDependencyResolver
{
    private readonly IUnityContainer container;

    public UnityDependencyResolver() : this(new UnityContainer())
    {
        var configuration = (UnityConfigurationSection) ConfigurationManager.GetSection("unity");
        if (configuration != null)
            configuration.Containers.Default.Configure(container);
    }

    public UnityDependencyResolver(IUnityContainer container)
    {
        Check.Argument.IsNotNull(container, "container");

        this.container = container;
        this.container.AddExtension(new TypeTrackingExtension());
        this.container.RegisterInstance<IUnityContainer>(container);
        this.container.RegisterInstance<IDependencyResolver>(this);
    }

    public IUnityContainer Container { get { return container; } }

    public void RegisterInstance<T>(T instance)
    {
        Check.Argument.IsNotNull(instance, "instance");

        container.RegisterInstance(instance);
    }

    public void RegisterType<TFrom, TTo>() where TTo : TFrom
    {
        container.RegisterType<TFrom, TTo>();
    }

    public void RegisterType(Type from, Type to)
    {
        Check.Argument.IsNotNull(from, "from");
        Check.Argument.IsNotNull(to, "to");

        container.RegisterType(from, to);
    }

    public void Inject<T>(T existing)
    {
        Check.Argument.IsNotNull(existing, "existing");

        container.BuildUp(existing);
    }

    public object Resolve(Type type)
    {
        Check.Argument.IsNotNull(type, "type");
        if (container.Configure<TypeTrackingExtension>().CanResolve(type))
        {
            return container.Resolve(type);
        }
        else
        {
            return null;
        }
    }

    public object Resolve(Type type, string name)
    {
        Check.Argument.IsNotNull(type, "type");
        if (Container.Configure<TypeTrackingExtension>().CanResolve(type, name))
        {
            return container.Resolve(type, name);
        }
        else
        {
            return null;
        }
    }

    public T Resolve<T>()
    {
        return (T) Resolve(typeof(T));
    }

    public T Resolve<T>(string name)
    {
        Check.Argument.IsNotEmpty(name, "name");
        return (T) Resolve(typeof(T), name);
    }

    public IEnumerable<T> ResolveAll<T>()
    {
        var namedInstances = container.ResolveAll<T>();
        var unnamedInstance = default(T);

        try
        {
            unnamedInstance = container.Resolve<T>();
        }
        catch (ResolutionFailedException)
        {
            //When default instance is missing
        }

        if (Equals(unnamedInstance, default(T)))
        {
            return namedInstances;
        }

        return new ReadOnlyCollection<T>(new List<T>(namedInstances) { unnamedInstance });
    }

    ~UnityDependencyResolver()
    {
        Dispose(false);
    }
    public void Dispose()
    {
        Dispose(true);
    }
    protected void Dispose(bool disposing)
    {
        if (disposing)
        {
            container.Dispose();
        }
    }
}

Though most methods are just direct wrappers for accessing the container itself, there are a few extra’s. For one, there’s the ResolveAll<T> method that returns both named and unnamed instances instead of only the named instances, that’s one problem fixed.

Secondly, you can see the Resolve methods use

if (Container.Configure<TypeTrackingExtension>().CanResolve(type, name))

It uses an UnityExtension to see if the Type can be resolved and it returns null if it can’t. This solution was provided by David Buksbaum in his blog post Type Tracking Extension for Unity. This extension is added to the container in this wrapper’s constructor.

I did modify David’s extension a little, to have it not overwrite the first registered type and to have CanResolve return true for types that can be initiated also (the original only returns true for types that have been registered). My version looks like this:

public class TypeTrackingExtension : UnityContainerExtension
{
    private readonly Dictionary<Type, HashSet<string>> registeredTypes = new Dictionary<Type, HashSet<string>>();

    protected override void Initialize()
    {
        Context.Container.Configure<UnityDefaultBehaviorExtension>().Remove();
        Context.Container.Configure<InjectedMembers>().Remove();
        //we have to be the first in the chain
        Context.RegisteringInstance += OnNewInstance;
        Context.Registering += OnNewType;

        Context.Container.Configure<UnityDefaultBehaviorExtension>().InitializeExtension(Context);
        Context.Container.Configure<InjectedMembers>().InitializeExtension(Context);
    }

    public override void Remove()
    {
        base.Remove();
        Context.RegisteringInstance -= OnNewInstance;
        Context.Registering -= OnNewType;
    }
    private void OnNewInstance(object sender, RegisterInstanceEventArgs e)
    {
        HashSet<string> names;
        string name = string.IsNullOrEmpty(e.Name) ? string.Empty : e.Name;

        if (!registeredTypes.TryGetValue(e.RegisteredType, out names))
        { //  not found, so add it
            registeredTypes.Add(e.RegisteredType, new HashSet<string> { name });
        }
        else
        { //  already added type, so add name
            if (name == String.Empty && names.Contains(name))
            {
                //default instance is already registered, let's give it a name so we can use ResolveAll() like it works in all other ioc containers
                name = e.Name = Guid.NewGuid().ToString();
            }
            names.Add(name);
        }
    }
    private void OnNewType(object sender, RegisterEventArgs e)
    {
        HashSet<string> names;
        string name = string.IsNullOrEmpty(e.Name) ? string.Empty : e.Name;
        if (!registeredTypes.TryGetValue(e.TypeFrom, out names))
        { //  not found, so add it
            registeredTypes.Add(e.TypeFrom, new HashSet<string> { name });
        }
        else
        { //  already added type, so add name
            if (name == String.Empty && names.Contains(name))
            {
                //default instance is already registered, let's give it a name so we can use ResolveAll() like it works in all other ioc containers
                name = e.Name = Guid.NewGuid().ToString();
            }
            names.Add(name);
        }
    }

    /// <summary>
    /// Determines whether this type can be resolved as the default.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <returns>
    /// 	<c>true</c> if this instance can resolve; otherwise, <c>false</c>.
    /// </returns>
    public bool CanResolve<T>()
    {
        return CanResolve(typeof(T), null);
    }
    /// <summary>
    /// Determines whether this type can be resolved as the default.
    /// </summary>
    /// <param name="type">The type.</param>
    /// <returns>
    /// 	<c>true</c> if this instance can resolve; otherwise, <c>false</c>.
    /// </returns>
    public bool CanResolve(Type type)
    {
        return CanResolve(type, null);
    }
    /// <summary>
    /// Determines whether this type can be resolved with the specified name.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="name">The name.</param>
    /// <returns>
    /// 	<c>true</c> if this instance can be resolved with the specified name; otherwise, <c>false</c>.
    /// </returns>
    public bool CanResolve<T>(string name)
    {
        return CanResolve(typeof (T), name);
    }

    /// <summary>
    /// Determines whether this type can be resolved with the specified name.
    /// </summary>
    /// <param name="type">The type.</param>
    /// <param name="name">The name.</param>
    /// <returns>
    /// 	<c>true</c> if this instance can be resolved with the specified name; otherwise, <c>false</c>.
    /// </returns>
    public bool CanResolve(Type type, string name)
    {
        if (isResolvableClass(type))
            return true;

        HashSet<string> names;
        if (registeredTypes.TryGetValue(type, out names))
        {
            return names.Contains(name ?? string.Empty);
        }
        return false;
    }

    private bool isResolvableClass(Type type)
    {
        return type.IsClass && !type.IsAbstract;
    }
    /// <summary>
    /// Determines whether this instance can be resolved at all.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <returns>
    /// 	<c>true</c> if this instance can be resolved at all; otherwise, <c>false</c>.
    /// </returns>
    public bool CanResolveAny<T>()
    {
        return CanResolveAny(typeof(T));
    }

    /// <summary>
    /// Determines whether this instance can be resolved at all.
    /// </summary>
    /// <param name="type">The type.</param>
    /// <returns>
    /// 	<c>true</c> if this instance can be resolved at all; otherwise, <c>false</c>.
    /// </returns>
    public bool CanResolveAny(Type type)
    {
        return isResolvableClass(type) || registeredTypes.ContainsKey(type);
    }

    /// <summary>
    /// Tries to resolve the type, returning null if not found.
    /// </summary>
    /// <typeparam name="T">The type to try and resolve.</typeparam>
    /// <returns>An object of type <see cref="T"/> if found, or <c>null</c> if not.</returns>
    public T TryResolve<T>()
    {
        return TryResolve<T>(default(T));
    }
    /// <summary>
    /// Tries to resolve the type with the specified of name, returning null if not found.
    /// </summary>
    /// <typeparam name="T">The type to try and resolve.</typeparam>
    /// <param name="name">The name associated with the type.</param>
    /// <returns>An object of type <see cref="T"/> if found, or <c>null</c> if not.</returns>
    public T TryResolve<T>(string name)
    {
        return TryResolve<T>(name, default(T));
    }
    /// <summary>
    /// Tries to resolve the type, returning null if not found.
    /// </summary>
    /// <typeparam name="T">The type to try and resolve.</typeparam>
    /// <param name="defaultValue">The default value to return if type not found.</param>
    /// <returns>An object of type <see cref="T"/> if found, or the <see cref="defaultValue"/> if not.</returns>
    public T TryResolve<T>(T defaultValue)
    {
        if (!CanResolve<T>())
            return defaultValue;
        return Container.Resolve<T>();
    }
    /// <summary>
    /// Tries to resolve the type with the specified of name, returning null if not found.
    /// </summary>
    /// <typeparam name="T">The type to try and resolve.</typeparam>
    /// <param name="name">The name associated with the type.</param>
    /// <param name="defaultValue">The default value to return if type not found.</param>
    /// <returns>An object of type <see cref="T"/> if found, or the <see cref="defaultValue"/> if not.</returns>
    public T TryResolve<T>(string name, T defaultValue)
    {
        if (!CanResolve<T>(name))
            return defaultValue;
        return Container.Resolve<T>(name);
    }
}

As you can see, I change the order of the event chain, by removing UnityDefaultBehaviorExtension from the Container, and then add it again later. This allows us to add a name to the type being registered. If a type is registered multiple times without a name given, a name is given in the form of a unique Guid

So now, if you do

Container.Register<IMyInterFace, MyClass1>();
Container.Register<IMyInterFace, MyClass2>();

var wrapper = new UnityDependencyResolver(Container);
var classes = wrapper.ResolveAll<IMyInterFace>()

classes will contain both MyClass1 and MyClass2!



kick it on DotNetKicks.com

c# Chris van de Steeg 16 Apr 2009 3 Comments

Fluent NHibernate’s AutoPersistenceModel: I Love it!

I checked out the latest version of Fluent NHibernate today and noticed the AutoPersistenceModel. I looked at the unit-tests to see what it’s supposed to do and I loved what I saw…

Let’s say you have a 2 simple classes like this:

image

Now, in the global.asax’s init (assuming a web application), we can configure NHibernate using Fluent NHibernate like this:

image

It uses convention over configuration in lots of places, eg the Id property is always used as identity-column if a property with that name exists.
But you could also easily add your own conventions. If you want to have the Id colums to be ArtistId and AlbumId (and any other className + Id), you’d do:

image

Want to restrict the namespace as well? No problem!

image

Fantastic! Now, to see what mapping file this code automagically creates for our Artist class, we can run the following code:

image

which returns an XmlDocument. In this case, the InnerXml of that document looks like this:

image

Again: fantastic! See how it even generates the one-to-many relation with the correct end-class, because we defined a property IList<Album>!

Running the same code for the Album class gives:

image

If you want to use Fluent NHibernate the ‘old’ way, you can still add ClassMap<Artist> to your assembly. Hence, you can even mix it with the AutoPersistenceModel! If you have a classmap file, it’ll use that for your class, if it isn’t there it’ll automatically create a mapping for you!

I’m sold! This makes using NHibernate a breeze. You can get up and running with your NHibernate project so much faster now.



kick it on DotNetKicks.com

.net & c# Chris van de Steeg 02 Dec 2008 11 Comments

jQuery ajax with asp.net mvc preview 5

Quite some had changed between mvc p4 and mvc p5, so it took some time too update my jquery4mvc project to preview 5. Be sure to check out scott’s post to read all the new stuff. He’ll be posting on the ajaxhelpers some time soon also.  If you wish to skip the reading and directly download the stuff: it’s at codeplex.

The javascript-only package includes 3 javascript files that allow you to use the default Microsoft AjaxHelper. You can just copy those files to your Content folder and include them in your head section, instead of the MicrosoftAjax.js and MicrosoftMvcAjax.js. All ajax extensions work the same as their Microsoft equivalence,  using jQuery instead of MicrosoftAjax. As a little bonus, you’ll get back and forward button support for your ajax-links.

image

That’s it, go ahead and use the AjaxHelper functions like you’re used to. Though a few things have changed for the AjaxHelpers in preview 5, you could still use the introduction ASP.NET MVC Preview 4 – Using Ajax and Ajax.Form by Scott Hanselman if you haven’t already checked out the AjaxHelper. Main thing that has changed is that you cannot use inline javascript in the AjaxOptions in preview 5, you should now specify a method name. You could also download the entire jQueryMvc project, it holds a sample website showing some of the ajax magic.

Talking about the entire project, it’s more than just the .js files! The intention of the project is to get you up and running very quickly when you want to create an mvc based ajax application. We use Unity as our default IoC container.

I think it’s quite hard to explain exactly what the project does for you, it’s best really to just look at the sample website, but I will give a brief overview. First, we have a DefaultViewViewEngine. If you mark your controller with a [DefaultView] attribute like so:

image

If you call in example /Home/Index, by default the Index view will be searched for. If it isn’t found, the DefaultViewViewEngine will look for a template with the name specified ("default" in the above example). It doesn’t matter what viewengine you use for your views, it will work for all of them. So what can this do? Look at the structure of the views in the sample site:

image

As you can see, most of the the views only have an ascx file prefixed with an underscore. Since the views are not found when the actions Home/About, Home/SayHello, Home/Index are called upon, the DefaultViewViewEngine will open Shared/Default.aspx.
This default page does not do muchimage

As you can see, it just uses the masterpage. But with only little imagination, you can see that you can easily create different default-pages for each controller. The masterpage however, does hold some extra magic:

image

This special contentplaceholder, by default works like a normal placeholder. But, if it doesn’t get new content from it’s page, it will ask the ViewEngine(s) to open the view of the current action prefixed with an underscore. So, if you call Home/About, this will ask for Home/_About. 
Can you see the magic? For all similar pages, you just have to create the ascx files (or other partials if you use a different viewengine). Those partial views will be pushed into the main page.

But wait, there’s more! If you make an ajax-request to a controller that has the [AjaxController] attribute, it will return only the partial view! Now, isn’t that great ? That looks a lot like the updatepanel to me :)

Go to codeplex and download the project to see the ajax-magic I’m so excited about!
Source can be downloaded at Google code: http://code.google.com/p/jquerymvc/source/checkout
The sample website can be seen in action at: http://www.chrisvandesteeg.nl/demo/jquerymvc5/



kick it on DotNetKicks.com

Ajax & asp.net mvc & c# & javascript Chris van de Steeg 16 Sep 2008 9 Comments

Next Page »

Recommended: Buy movies online.