Giter Site home page Giter Site logo

nancy.bootstrappers.unity's Introduction

A bootstrapper implementation, for the Nancy framework, based on the Unity inversion of control container.

Usage

When Nancy detects that the UnityNancyBootstrapper type is available in the AppDomain of your application, it will assume you want to use it, rather than the default one.

The easiest way to get the latest version of UnityNancyBootstrapper into your application is to install the Nancy.Bootstrappers.Unity nuget.

Customizing

By inheriting from UnityNancyBootstrapper you will gain access to the IUnityContainer of the application and request containers and can perform what ever registrations that your application requires.

public class Bootstrapper : UnityNancyBootstrapper
{
    protected override void ApplicationStartup(IUnityContainer container, IPipelines pipelines)
    {
        // No registrations should be performed in here, however you may
        // resolve things that are needed during application startup.
    }

    protected override void ConfigureApplicationContainer(IUnityContainer existingContainer)
    {
        // Perform registation that should have an application lifetime
    }

    protected override void ConfigureRequestContainer(IUnityContainer container, NancyContext context)
    {
        // Perform registrations that should have a request lifetime
    }

    protected override void RequestStartup(IUnityContainer container, IPipelines pipelines, NancyContext context)
    {
        // No registrations should be performed in here, however you may
        // resolve things that are needed during request startup.
    }
}

You can also override the GetApplicationContainer method and return a pre-existing container instance, instead of having Nancy create one for you. This is useful if Nancy is co-existing with another application and you want them to share a single container.

protected override IUnityContainer GetApplicationContainer()
{
    // Return application container instance
}

If you end up overriding GetApplicationContainer(), you will have to manually add the EnumerableExtension to your container so that it is able to resolve IEnumerable<T> types properly (something that Unity has poor support for).

container.AddNewExtension<EnumerableExtension>();

Code of Conduct

This project has adopted the code of conduct defined by the Contributor Covenant to clarify expected behavior in our community. For more information see the .NET Foundation Code of Conduct.

Contribution License Agreement

Contributing to Nancy requires you to sign a contribution license agreement (CLA) for anything other than a trivial change. By signing the contribution license agreement, the community is free to use your contribution to .NET Foundation projects.

.NET Foundation

This project is supported by the .NET Foundation.

Copyright

Copyright © 2010 Andreas Håkansson, Steven Robbins and contributors

License

Nancy.Bootstrappers.Unity is licensed under MIT. Refer to license.txt for more information.

nancy.bootstrappers.unity's People

Contributors

asizikov avatar ayoung avatar cemremengu avatar grumpydev avatar horsdal avatar jchannon avatar khellang avatar thecodejunkie avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nancy.bootstrappers.unity's Issues

UnityEnumerableShip<T> replacement

Hello,

Guys, I think UnityEnumerableShip can be replaced with unity extension which can allow to resolve IEnumerable with more natural way.

Unity extension

    /// <summary>
    /// Adds the <see cref="EnumerableResolutionStrategy"/> to container's strategies.
    /// </summary>
    public class EnumerableResolutionExtension : UnityContainerExtension
    {
        /// <summary>
        /// Initial the container with this extension's functionality.
        /// </summary>
        /// <remarks>
        /// When overridden in a derived class, this method will modify the given
        /// <see cref="T:Microsoft.Practices.Unity.ExtensionContext" /> by adding strategies, policies, etc. to
        /// install it's functions into the container.
        /// </remarks>
        protected override void Initialize()
        {
            Context.Strategies.Add(new EnumerableResolutionStrategy(), UnityBuildStage.TypeMapping);
        }
    }

Strategy

    /// <summary>
    /// Allows to resolve generic IEnumerable`1 types
    /// </summary>
    internal class EnumerableResolutionStrategy : IBuilderStrategy
    {
        /// <summary>
        /// This method replaces the build key used to resolve <see cref="IEnumerable{T}"/>.
        /// </summary>
        /// <param name="context">Context of the build operation.</param>
        public void PreBuildUp(IBuilderContext context)
        {
            if (context.BuildKey.Type.IsGenericType && context.BuildKey.Type.FullName.StartsWith("System.Collections.Generic.IEnumerable"))
            {
                var arrayType = context.BuildKey.Type.GetGenericArguments()[0].MakeArrayType();
                context.BuildKey = new NamedTypeBuildKey(arrayType, context.BuildKey.Name);
            }
        }

        /// <summary>
        /// This method does nothing.
        /// </summary>
        /// <param name="context">Context of the build operation.</param>
        public void PostBuildUp(IBuilderContext context)
        {
        }

        /// <summary>
        /// This method does nothing.
        /// </summary>
        /// <param name="context">Context of the build operation.</param>
        public void PreTearDown(IBuilderContext context)
        {
        }

        /// <summary>
        /// This method does nothing.
        /// </summary>
        /// <param name="context">Context of the build operation.</param>
        public void PostTearDown(IBuilderContext context)
        {
        }
    }

And Nancy bootstrapper

        /// <summary>
        /// Gets the application level container
        /// </summary>
        /// <returns>Container instance</returns>
        protected override IUnityContainer GetApplicationContainer()
        {
            var container = new UnityContainer();
            container.AddExtension(new EnumerableResolutionExtension());
            return container;
        }

        /// <summary>
        /// Register the default implementations of internally used types into the container as singletons
        /// </summary>
        /// <param name="container">Container to register into</param>
        /// <param name="typeRegistrations">Type registrations to register</param>
        protected override void RegisterTypes(IUnityContainer container, IEnumerable<TypeRegistration> typeRegistrations)
        {
            foreach (var typeRegistration in typeRegistrations)
            {
                switch (typeRegistration.Lifetime)
                {
                    case Lifetime.Transient:
                        container.RegisterType(
                            typeRegistration.RegistrationType,
                            typeRegistration.ImplementationType,
                            new TransientLifetimeManager());
                        break;
                    case Lifetime.Singleton:
                        container.RegisterType(
                            typeRegistration.RegistrationType,
                            typeRegistration.ImplementationType,
                            new ContainerControlledLifetimeManager());
                        break;
                    case Lifetime.PerRequest:
                        throw new InvalidOperationException("Unable to directly register a per request lifetime.");
                    default:
                        throw new ArgumentOutOfRangeException();
                }
            }

            // REMOVED SHIM HERE

            // Added this in here because Unity doesn't seem to support
            // resolving using the greediest resolvable constructor
            container.RegisterType<IFileSystemReader, DefaultFileSystemReader>(new        ContainerControlledLifetimeManager());
        }

Update Unity dependency?

Hi. I've just installed the Unity bootstrapper and VS complains that IUnityContainer is registered in version Microsoft.Practices.Unity 2.1.505 and I pulled Unity 4.0. Is there a reason not to upgrade?

The resently added EnumerableResolutionStrategy does not seem to work.

The projects in the solution won't build. Several files are missing.

Appart from that, i think there is a problem with the recent change about EnumerableResolutionStrategy.

Try the sample on this site:

http://www.stefanbader.ch/minimal-sample-self-hosted-nancy-using-owin-unity-bootstrapper-including-xunit-test/

and update the NuGet-package to 1.2. It will throw the following exception:

Resolution of the dependency failed, type = "Nancy.Bootstrapper.IApplicationStartup", name = "Nancy.ViewEngines.ViewEngineApplicationStartup". Exception occurred while: while resolving.

Exception is: InvalidOperationException - The current type, System.Collections.Generic.IEnumerable`1[Nancy.ViewEngines.IViewEngine], is an interface and cannot be constructed. Are you missing a type mapping?

At the time of the exception, the container was:

Resolving Nancy.ViewEngines.ViewEngineApplicationStartup,Nancy.ViewEngines.ViewEngineApplicationStartup (mapped from Nancy.Bootstrapper.IApplicationStartup, Nancy.ViewEngines.ViewEngineApplicationStartup) Resolving parameter "viewEngines" of constructor Nancy.ViewEngines.ViewEngineApplicationStartup(System.Collections.Generic.IEnumerable1[[Nancy.ViewEngines.IViewEngine, Nancy, Version=1.2.0.0, Culture=neutral, PublicKeyToken=null]] viewEngines, Nancy.ViewEngines.IViewCache viewCache, Nancy.ViewEngines.IViewLocator viewLocator)
Resolving System.Collections.Generic.IEnumerable1[Nancy.ViewEngines.IViewEngine],(none)

The current type, System.Collections.Generic.IEnumerable`1[Nancy.ViewEngines.IViewEngine], is an interface and cannot be constructed. Are you missing a type mapping?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.