您的位置:首页 > 其它

在 MVC 控制器中使用 构造函数时行依赖注入 (IoC)

2015-03-28 17:08 405 查看
在 Controller 中使用 构造函数进行依赖注入 (IoC)

1. Controller 代码:

ICard card;
ICardCategory cardCategory;
public CardController(ICard card, ICardCategory cardCategory)
{
this.card = card;
this.cardCategory = cardCategory;
}


接口 ICard , ICardCateogry 是一个普通的接口,没有继承或实现任何接口,而需要做的就是在 Gloable.cs 文件中解析依赖, 为了方便复用,将解析依赖封装成一个类,然后在 Gloable.cs 文件中注册,在这个示例中,使用的是 Unity 进行依赖注入,完整的代码如下:

using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
//using System.Web.Http.Dependencies;
using System.Web;
using System.Web.Mvc;

namespace SnsManage.Resolver
{
/// <summary>
///  Dependency Injection  Resolver Container
/// </summary>
public class UnityResolver : IDependencyResolver
{
protected IUnityContainer container;

public UnityResolver(IUnityContainer container)
{
if (container == null)
{
throw new ArgumentNullException("container");
}
this.container = container;
}

public object GetService(Type serviceType)
{
try
{
return container.Resolve(serviceType);
}
catch (ResolutionFailedException)
{
return null;
}
}

public IEnumerable<object> GetServices(Type serviceType)
{
try
{
return container.ResolveAll(serviceType);
}
catch (ResolutionFailedException)
{
return new List<object>();
}
}

//public IDependencyScope BeginScope()
//{
//    var child = container.CreateChildContainer();
//    return new UnityResolver(child);
//}

//public void Dispose()
//{
//    container.Dispose();
//}

//private const string HttpContextKey = "perRequestContainer";

//private readonly IUnityContainer container;

//public UnityResolver(IUnityContainer container)
//{
//    this.container = container;
//}

//public object GetService(Type serviceType)
//{
//    if (typeof(IController).IsAssignableFrom(serviceType))
//    {
//        return ChildContainer.Resolve(serviceType);
//    }

//    return IsRegistered(serviceType) ? ChildContainer.Resolve(serviceType) : null;
//}

//public IEnumerable<object> GetServices(Type serviceType)
//{
//    if (IsRegistered(serviceType))
//    {
//        yield return ChildContainer.Resolve(serviceType);
//    }

//    foreach (var service in ChildContainer.ResolveAll(serviceType))
//    {
//        yield return service;
//    }
//}

//protected IUnityContainer ChildContainer
//{
//    get
//    {
//        var childContainer = HttpContext.Current.Items[HttpContextKey] as IUnityContainer;

//        if (childContainer == null)
//        {
//            HttpContext.Current.Items[HttpContextKey] = childContainer = container.CreateChildContainer();
//        }

//        return childContainer;
//    }
//}

//public static void DisposeOfChildContainer()
//{
//    var childContainer = HttpContext.Current.Items[HttpContextKey] as IUnityContainer;

//    if (childContainer != null)
//    {
//        childContainer.Dispose();
//    }
//}

//private bool IsRegistered(Type typeToCheck)
//{
//    var isRegistered = true;

//    if (typeToCheck.IsInterface || typeToCheck.IsAbstract)
//    {
//        isRegistered = ChildContainer.IsRegistered(typeToCheck);

//        if (!isRegistered && typeToCheck.IsGenericType)
//        {
//            var openGenericType = typeToCheck.GetGenericTypeDefinition();

//            isRegistered = ChildContainer.IsRegistered(openGenericType);
//        }
//    }

//    return isRegistered;
//}
}
}


View Code
然后在 App_Start 文件中添加一个配置类, UnityConfig.cs, 其中的代码如下:

public static class UnityConfig
{
/// <summary>
///  Dependency Injection
/// </summary>
public static void RegisterComponents()
{
var container = new UnityContainer();

// register all your components with the container here
// it is NOT necessary to register your controllers

// e.g. container.RegisterType<ITestService, TestService>();

container.RegisterType<IUser, UserService>( new HierarchicalLifetimeManager());

DependencyResolver.SetResolver(new UnityResolver(container));

}
}


最后在 Global.asax 文件中注册

UnityConfig.RegisterComponents();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐