Skip to content

Instantly share code, notes, and snippets.

@kveratis
Created December 14, 2012 00:13
Show Gist options
  • Save kveratis/4281333 to your computer and use it in GitHub Desktop.
Save kveratis/4281333 to your computer and use it in GitHub Desktop.
Microsoft Unity dependency injection module.
using System;
using System.Data;
using Company.Repositories;
using Company.Repositories.Sql;
using Microsoft.Practices.Unity;
namespace Company
{
public partial class LeadAdd : WebPage
{
// The dependencies will be automatically resolved for pages and user controls by the module using unity.
#region Unity
[Dependency("leads")]
public ILeadRepository Leads { get; set; }
[Dependency("contacts")]
public IContactRepository Contacts { get; set; }
[Dependency("redisUsers")]
public IUserRepository Users { get; set; }
#endregion
}
}
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.IO;
using System.Net.Mail;
using System.Text;
using System.Web;
using System.Web.Security;
using Company.Modules;
using Company.Repositories.Sql;
using Microsoft.Practices.Unity;
using Company.Repositories;
using Company.Model;
using Company.Service;
using ServiceStack.Redis;
using Harbour.RedisSessionStateStore;
namespace Company
{
public class Global : HttpApplication
{
protected void Application_Start(Object sender, EventArgs e)
{
// Setup Unity
Application.GetContainer().ConfigureContainer();
IRedisClientsManager clientManager = Application.GetContainer().Resolve<IRedisClientsManager>("redisClientManager");
RedisSessionStateStoreProvider.SetClientManager(clientManager);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")]
protected void Application_End(Object sender, EventArgs e)
{
#region Unity Dispose
IUnityContainer applicationContainer = Application.GetContainer();
if (applicationContainer != null)
{
applicationContainer.Dispose();
}
#endregion
}
}
}
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using System.Diagnostics;
namespace CompanyNameSpace.Infrastructure
{
public static class HttpApplicationStateExtensions
{
private const string GlobalContainerKey = "UnityContainer";
public static IUnityContainer GetContainer(this HttpApplicationState appState)
{
appState.Lock();
try
{
var myContainer = appState[GlobalContainerKey] as IUnityContainer;
if (myContainer == null)
{
myContainer = new UnityContainer();
appState[GlobalContainerKey] = myContainer;
}
return myContainer;
}
finally
{
appState.UnLock();
}
}
public static void ConfigureContainer(this IUnityContainer container)
{
container.LoadConfiguration("application");
}
}
public sealed class UnityWebFormsHttpModule : IHttpModule
{
private HttpApplication context;
private IUnityContainer container;
public void Init(HttpApplication context)
{
this.context = context;
this.context.PreRequestHandlerExecute += OnPreRequestHandlerExecute;
}
public void Dispose()
{
}
private IUnityContainer Container
{
get
{
if (container == null)
container = context.Application.GetContainer();
return container;
}
}
/// <summary>
/// Resolve dependencies marked with the <see cref="Microsoft.Practices.Unity.DependencyAttribute"/>. Also
/// sets dependencies for UserControls to be resolved on the Page.InitComplete event.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnPreRequestHandlerExecute(object sender, EventArgs e)
{
IHttpHandler currentHandler = HttpContext.Current.Handler as Page;
if (currentHandler != null)
{
Container.BuildUp(currentHandler.GetType(), currentHandler);
//User Controls are ready to be built up after page initialization is complete
var currentPage = currentHandler as Page;
if (currentPage != null)
{
currentPage.InitComplete += OnPageInitComplete;
}
}
}
/// <summary>
/// Build up dependencies marked with <see cref="Microsoft.Practices.Unity.DependencyAttribute"/> each control in the
/// page's control tree.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnPageInitComplete(object sender, EventArgs e)
{
var currentPage = sender as Page;
List<Control> controls = new List<Control>();
GetUserControlTree(currentPage, controls);
foreach (Control c in controls)
{
container.BuildUp(c.GetType(), c);
}
this.context.PreRequestHandlerExecute -= OnPreRequestHandlerExecute;
}
//
/// <summary>
/// Get only the user controls in the page's control tree.
/// </summary>
/// <param name="root"></param>
/// <returns></returns>
private void GetUserControlTree(Control root, List<Control> controls)
{
if (root.GetType().Name.EndsWith("_ascx"))
{
controls.Add(root);
}
if (root.HasControls())
{
foreach (Control control in root.Controls)
{
GetUserControlTree(control, controls);
}
}
}
}
}
<configuration>
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
</configSections>
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<alias alias="IRedisClientsManager" type="ServiceStack.Redis.IRedisClientsManager, ServiceStack.Interfaces" />
<alias alias="PooledRedisClientManager" type="ServiceStack.Redis.PooledRedisClientManager, ServiceStack.Redis" />
<!-- Repositories -->
<alias alias="IUserRepository" type="CompanyNameSpace.Repositories.IUserRepository, CompanyNameSpace.Core" />
<alias alias="SqlUserRepository" type="CompanyNameSpace.Repositories.Sql.SqlUserRepository, CompanyNameSpace.Core" />
<alias alias="RedisUserRepository" type="CompanyNameSpace.Repositories.Redis.RedisUserRepository, CompanyNameSpace.Core" />
<alias alias="IUserRoleRepository" type="CompanyNameSpace.Repositories.IUserRoleRepository, CompanyNameSpace.Core" />
<alias alias="SqlUserRoleRepository" type="CompanyNameSpace.Repositories.Sql.SqlUserRoleRepository, CompanyNameSpace.Core" />
<!-- Services -->
<alias alias="IAuthenticationService" type="CompanyNameSpace.Service.IAuthenticationService, CompanyNameSpace.Core" />
<alias alias="CacheAuthenticationService" type="CompanyNameSpace.Service.CacheAuthenticationService, CompanyNameSpace.Core" />
<alias alias="ActiveDirectoryAuthenticationService" type="CompanyNameSpace.Service.ActiveDirectoryAuthenticationService, CompanyNameSpace.Core" />
<alias alias="SqlAuthenticationService" type="CompanyNameSpace.Service.SqlAuthenticationService, CompanyNameSpace.Core" />
<alias alias="IMembershipService" type="CompanyNameSpace.Service.IMembershipService, CompanyNameSpace.Core" />
<alias alias="MyMembershipService" type="CompanyNameSpace.Service.MyMembershipService, CompanyNameSpace.Core" />
<container name="application">
<register type="IRedisClientsManager" mapTo="PooledRedisClientManager" name="redisClientManager">
<lifetime type="singleton" />
<constructor>
<param name="readWriteHosts">
<array>
<value value="192.168.10.232:6379" />
</array>
</param>
</constructor>
</register>
<!-- Repositories -->
<register type="ISettingsRepository" mapTo="ConfigurationFileSettingsRepository">
<lifetime type="singleton" />
<constructor />
</register>
<register type="IUserRepository" mapTo="SqlUserRepository" name="sqlUsers">
<lifetime type="singleton" />
<constructor />
</register>
<register type="IUserRepository" mapTo="RedisUserRepository" name="redisUsers">
<lifetime type="singleton" />
<constructor>
<param name="appKey" value="sci" />
<param name="clientManager" dependencyName="redisClientManager" />
<param name="fallback" dependencyName="sqlUsers" />
</constructor>
</register>
<register type="IUserRoleRepository" mapTo="SqlUserRoleRepository" name="roles">
<lifetime type="singleton" />
<constructor />
</register>
<!-- Services -->
<register type="IAuthenticationService" mapTo="SqlAuthenticationService" name="database">
<lifetime type="singleton" />
<constructor>
<param name="domain" value="sci" />
<param name="userRepository" dependencyName="sqlUsers" />
</constructor>
</register>
<register type="IAuthenticationService" mapTo="ActiveDirectoryAuthenticationService" name="company">
<lifetime type="singleton" />
<constructor>
<param name="domain" value="company.com" />
<param name="path" value="LDAP://DC1.company.com:389/DC=company,DC=com" />
<param name="fallback" dependencyName="database" />
</constructor>
</register>
<register type="IAuthenticationService" mapTo="ActiveDirectoryAuthenticationService" name="customer">
<lifetime type="singleton" />
<constructor>
<param name="domain" value="CUSTOMER" />
<param name="path" value="LDAP://dc1.customer.com:3269/DC=customer,DC=com@CUSTOMER|LDAP://ldaps.customer.com:3269/DC=com" />
<param name="fallback" dependencyName="company" />
</constructor>
</register>
<register type="IAuthenticationService" mapTo="CacheAuthenticationService" name="redisAuth">
<lifetime type="singleton" />
<constructor>
<param name="repository" dependencyName="redis" />
<param name="fallback" dependencyName="customer" />
</constructor>
</register>
<register type="IMembershipService" mapTo="MyMembershipService">
<lifetime type="singleton" />
<constructor>
<param name="authenticationService" dependencyName="redisAuth" />
<param name="userRepository" dependencyName="redisUsers" />
<param name="impersonationUserId" value="12345" />
</constructor>
</register>
</container>
</unity>
<system.web>
<httpModules>
<add name="UnityWebFormsHttpModule" type="Company.Modules.UnityWebFormsHttpModule, Company.Core" />
</httpModules>
</system.web>
</configuration>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment