All infos - IOC Castle Windsor on WebApi .net framework
18
дек

IOC Castle Windsor on WebApi .net framework

Для добавления контейнера Castle Windsor нужно:

1. Добавить  nuget Castle Windsor в Visual Studio.

2. Добавить Composition Root:

public class WindsorCompositionRoot : IHttpControllerActivator
    {
        private readonly IWindsorContainer container;

        public WindsorCompositionRoot(IWindsorContainer container)
        {
            this.container = container;
        }

        public IHttpController Create(
            HttpRequestMessage request,
            HttpControllerDescriptor controllerDescriptor,
            Type controllerType)
        {
            var controller =
                (IHttpController)container.Resolve(controllerType);

            request.RegisterForDispose(
                new Release(
                    () => container.Release(controller)));

            return controller;
        }

        private class Release : IDisposable
        {
            private readonly Action release;

            public Release(Action release)
            {
                this.release = release;
            }

            public void Dispose()
            {
                release();
            }
        }
    }

 Добаляем инсталлер:

public class ApplicationCastleInstaller: IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            var controllers = Assembly.GetExecutingAssembly()
                .GetTypes().Where(x => x.BaseType == typeof(ApiController)).ToList();
            foreach (var controller in controllers)
            {
                container.Register(Component.For(controller).LifestyleTransient());
            }

            container.Register(Component.For().ImplementedBy()
                .LifestyleTransient());
            container.Register(Component.For().ImplementedBy()
                .DependsOn(Dependency.OnValue("connectionString", ConfigurationManager.ConnectionStrings["ConnetionName"].ConnectionString)).LifestyleTransient());
        }
    }

 В Global.asax заменяем дефолтную реализацию IHttpControllerActivator на наш WindsorCompositionRoot:

public class WebApiApplication : HttpApplication
    {
        private readonly IWindsorContainer container;

        public WebApiApplication()
        {
            container =
                new WindsorContainer().Install(new ApplicationCastleInstaller());
        }

        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);
            GlobalConfiguration.Configuration.Services.Replace(
                typeof(IHttpControllerActivator),
                new WindsorCompositionRoot(container));
            GlobalConfiguration.Configuration.Filters.Add(new ExceptionFilter());
        }
    }

Share this post