Skip to content
This repository has been archived by the owner on Jan 20, 2023. It is now read-only.

Castle Windsor DI Container Adapter for WebForms #5

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions WebFormsDependencyInjection.sln
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{20D2AF61-C
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.AspNet.WebFormsDependencyInjection.Unity.Test", "test\UnityAdapter.Test\Microsoft.AspNet.WebFormsDependencyInjection.Unity.Test.csproj", "{071D67ED-B0B6-4927-A75D-83DDDC4DD60B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.AspNet.WebFormsDependencyInjection.CastleWindsor", "src\CastleWindsorAdapter\Microsoft.AspNet.WebFormsDependencyInjection.CastleWindsor.csproj", "{D1A617C8-84FF-4DA8-85B0-0563EC57FD28}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.AspNet.WebFormsDependencyInjection.CastleWindsor.Test", "test\CastleWindsorAdapter.Test\Microsoft.AspNet.WebFormsDependencyInjection.CastleWindsor.Test.csproj", "{B83327D3-924D-46C0-A327-0B258FBF0D8C}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -25,13 +29,23 @@ Global
{071D67ED-B0B6-4927-A75D-83DDDC4DD60B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{071D67ED-B0B6-4927-A75D-83DDDC4DD60B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{071D67ED-B0B6-4927-A75D-83DDDC4DD60B}.Release|Any CPU.Build.0 = Release|Any CPU
{D1A617C8-84FF-4DA8-85B0-0563EC57FD28}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D1A617C8-84FF-4DA8-85B0-0563EC57FD28}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D1A617C8-84FF-4DA8-85B0-0563EC57FD28}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D1A617C8-84FF-4DA8-85B0-0563EC57FD28}.Release|Any CPU.Build.0 = Release|Any CPU
{B83327D3-924D-46C0-A327-0B258FBF0D8C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B83327D3-924D-46C0-A327-0B258FBF0D8C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B83327D3-924D-46C0-A327-0B258FBF0D8C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B83327D3-924D-46C0-A327-0B258FBF0D8C}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{3E53288E-F0D1-4A06-8FF9-7DC8FADFDC62} = {7A7363E1-8E17-4C97-9B94-6BAF1E422361}
{071D67ED-B0B6-4927-A75D-83DDDC4DD60B} = {20D2AF61-CF65-409C-95A4-DEA4C9B605F6}
{D1A617C8-84FF-4DA8-85B0-0563EC57FD28} = {7A7363E1-8E17-4C97-9B94-6BAF1E422361}
{B83327D3-924D-46C0-A327-0B258FBF0D8C} = {20D2AF61-CF65-409C-95A4-DEA4C9B605F6}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {1B769C6E-7263-47BE-899F-95CA7A165C3F}
Expand Down
39 changes: 39 additions & 0 deletions src/CastleWindsorAdapter/CastleWindsorAdapter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
namespace Microsoft.AspNet.WebFormsDependencyInjection.CastleWindsor
{
using Castle.Windsor;
using System.Web;

/// <summary>
/// Extension methods of HttpApplication that help use Castle Windsor container
/// </summary>
public static class CastleWindsorAdapter
{
private static object _lock = new object();

/// <summary>
/// Add a new Castle Windsor container in asp.net application. If there is WebObjectActivator already registered,
/// it will be chained up. When the new WebObjectActivator can't resolve the type, the previous WebObjectActivator
/// will be used. If the previous WebObjectActivator can't resolve it either, DefaultCreateInstance will be used
/// which creates instance through none public default constructor based on reflection.
/// </summary>
/// <returns></returns>
public static IWindsorContainer AddCastleWindsor()
{
lock (_lock)
{
HttpRuntime.WebObjectActivator = new ContainerServiceProvider(HttpRuntime.WebObjectActivator);

return GetContainer();
}
}

/// <summary>
/// Get most recent added Castle Windsor container
/// </summary>
/// <returns></returns>
public static IWindsorContainer GetContainer()
{
return (HttpRuntime.WebObjectActivator as ContainerServiceProvider)?.Container;
}
}
}
116 changes: 116 additions & 0 deletions src/CastleWindsorAdapter/ContainerServiceProvider.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
namespace Microsoft.AspNet.WebFormsDependencyInjection.CastleWindsor
{
using global::Castle.MicroKernel.Registration;
using global::Castle.MicroKernel.Resolvers;
using global::Castle.Windsor;
using global::Castle.MicroKernel;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Reflection;
using System.Web.Hosting;

/// <summary>
/// The Castle Windsor adapter for WebObjectActivator
/// </summary>
class ContainerServiceProvider : IServiceProvider, IRegisteredObject
{
private const int TypesCannontResolveCacheCap = 100000;
private readonly IServiceProvider _next;
private readonly ConcurrentDictionary<Type, bool> _typesCannotResolve = new ConcurrentDictionary<Type, bool>();

public IWindsorContainer Container { get; internal set; }

public ContainerServiceProvider(IServiceProvider next)
{
_next = next;
HostingEnvironment.RegisterObject(this);

Container = new WindsorContainer();
Container.Register(Component.For<ILazyComponentLoader>().ImplementedBy<WebFormsComponentsLoader>());
}

/// <summary>
/// Implementation of IServiceProvider. Asp.net will call this method to
/// create the instances of Page/UserControl/HttpModule etc.
/// </summary>
/// <param name="serviceType"></param>
/// <returns></returns>
public object GetService(Type serviceType)
{
//
// Try unresolvable types
if (_typesCannotResolve.ContainsKey(serviceType))
{
return DefaultCreateInstance(serviceType);
}

//
// Try the container
object result = null;

//
// registered component or WebForms type
if (Container.Kernel.HasComponent(serviceType) || serviceType.IsWebFormsComponent())
{
try
{
result = Container.Resolve(serviceType);
}
catch (ComponentNotFoundException)
{
// Ignore and continue
}
}

//
// Try the next provider
if (result == null)
{
result = _next?.GetService(serviceType);
}

//
// Default activation
if (result == null)
{
if ((result = DefaultCreateInstance(serviceType)) != null)
{
// Cache it so we don't need to bother container again
if (_typesCannotResolve.Count < TypesCannontResolveCacheCap)
{
_typesCannotResolve.TryAdd(serviceType, true);
}
}
}

return result;
}

public void Stop(bool immediate)
{
HostingEnvironment.UnregisterObject(this);
Container.Dispose();
}

internal IServiceProvider NextServiceProvider
{
get { return _next; }
}

internal IDictionary<Type, bool> TypeCannotResolveDictionary
{
get { return _typesCannotResolve; }
}

protected virtual object DefaultCreateInstance(Type type)
{
return Activator.CreateInstance(
type,
BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.CreateInstance,
null,
null,
null);
}
}
}
36 changes: 36 additions & 0 deletions src/CastleWindsorAdapter/HttpApplicationExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
namespace Microsoft.AspNet.WebFormsDependencyInjection.CastleWindsor
{
using global::Castle.Windsor;
using System;
using System.Web;

/// <summary>
/// Extension methods of HttpApplication that help use Castle Windsor container
/// </summary>
public static class HttpApplicationExtensions
{
/// <summary>
///
/// </summary>
/// <param name="application"></param>
/// <returns></returns>
public static IWindsorContainer AddCastleWindsor(this HttpApplication application)
{
if (application == null)
{
throw new ArgumentNullException(nameof(application));
}

return CastleWindsorAdapter.AddCastleWindsor();
}

/// <summary>
///
/// </summary>
/// <returns></returns>
public static IWindsorContainer GetCastleWindsorContainer(this HttpApplication application)
{
return CastleWindsorAdapter.GetContainer();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),WebFormsDependencyInjection.sln))\tools\CastleWindsorAdapter.settings.targets" />
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),WebFormsDependencyInjection.sln))\tools\WebFormsDependencyInjection.settings.targets" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{D1A617C8-84FF-4DA8-85B0-0563EC57FD28}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Microsoft.AspNet.WebFormsDependencyInjection.CastleWindsor</RootNamespace>
<AssemblyName>Microsoft.AspNet.WebFormsDependencyInjection.CastleWindsor</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<DocumentationFile>$(OutputPath)$(AssemblyName).xml</DocumentationFile>
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\..\</SolutionDir>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<BaseIntermediateOutputPath>..\obj\</BaseIntermediateOutputPath>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<BaseIntermediateOutputPath>..\obj\</BaseIntermediateOutputPath>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Runtime.Remoting" />
<Reference Include="System.Web" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
<Reference Include="Castle.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL">
<HintPath>..\..\packages\Castle.Core.4.2.0\lib\net45\Castle.Core.dll</HintPath>
</Reference>
<Reference Include="Castle.Windsor, Version=4.0.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL">
<HintPath>..\..\packages\Castle.Windsor.4.1.1\lib\net45\Castle.Windsor.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="CastleWindsorAdapter.cs" />
<Compile Include="ContainerServiceProvider.cs" />
<Compile Include="HttpApplicationExtensions.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="TypeExtensions.cs" />
<Compile Include="WebFormsComponentsLoader.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
25 changes: 25 additions & 0 deletions src/CastleWindsorAdapter/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Microsoft.AspNet.WebFormsDependencyInjection.CastleWindsor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyProduct("Microsoft.AspNet.WebFormsDependencyInjection.CastleWindsor")]
[assembly: AssemblyCopyright("\x00a9 Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3e53288e-f0d1-4a06-8ff9-7dc8fadfdc62")]

[assembly: InternalsVisibleTo("Microsoft.AspNet.WebFormsDependencyInjection.CastleWindsor.Test")]
16 changes: 16 additions & 0 deletions src/CastleWindsorAdapter/TypeExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
namespace Microsoft.AspNet.WebFormsDependencyInjection.CastleWindsor
{
using System;
using System.Globalization;
using System.Web;
using System.Web.UI;

public static class TypeExtensions
{
public static bool IsWebFormsComponent(this Type type)
{
return (typeof(UserControl).IsAssignableFrom(type) ||
typeof(IHttpHandler).IsAssignableFrom(type));
}
}
}
30 changes: 30 additions & 0 deletions src/CastleWindsorAdapter/WebFormsComponentsLoader.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
namespace Microsoft.AspNet.WebFormsDependencyInjection.CastleWindsor
{
using global::Castle.MicroKernel.Registration;
using global::Castle.MicroKernel.Resolvers;
using System;
using System.Collections;

/// <summary>
/// Lazy loader for dynamic ASP.NET types created in runtime
/// </summary>
public class WebFormsComponentsLoader : ILazyComponentLoader
{
public IRegistration Load(string name, Type service, IDictionary arguments)
{
if (service == null)
{
return null;
}

if (service.IsWebFormsComponent())
{
return Component.For(service)
.LifeStyle.Transient
.NamedAutomatically("webforms");
}

return null;
}
}
}
5 changes: 5 additions & 0 deletions src/CastleWindsorAdapter/packages.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Castle.Core" version="4.2.0" targetFramework="net472" />
<package id="Castle.Windsor" version="4.1.1" targetFramework="net472" />
</packages>
Loading