1

我想知道使用 IOC 容器是否有比下面代码项目示例中建议的方式更优雅的模式。当然,可以使用 IOC 容器,以便当您拥有可靠的 IOC 流程时,控制器构造函数是无参数的。这也意味着当您的应用程序具有比 MVC 更多(例如 WEB-API 和其他任何东西)时,您正在为该技术构建相同类型的解决方案。这对我来说看起来并不干燥。是否有人使用一种很好的模式来“注册”容器,例如 IMyMagicControllerHat 并使用一些不错的 .net 系统库获得单例?很明显,如果你有一个 UI Depends on Core Depends on Model 类型的应用程序,你会关心构建依赖和静态调用。对 MVCApplication 的静态回调与我有关。我一直在寻找更好的方法。

CODEProject 链接.... http://www.codeproject.com/Articles/99361/How-To-Use-Unity-Container-In-ASP-NET-MVC-Framewor

总之相关代码....

public interface IContainerAccessor
{
    IUnityContainer Container { get; }
}
public class MvcApplication : HttpApplication, IContainerAccessor
{
    private static IUnityContainer _container;
    public static IUnityContainer Container
    {
        get { return _container;        }
    }
    public static IUnityContainer Container
    {
        get  {   return _container;    }
    }

还有像 MS 这样的例子,它显示了一个自定义静态作为解决方案。http://msdn.microsoft.com/en-us/library/vstudio/hh323691%28v=vs.100%29.aspx 我期待可能有一个完善的适配器模式或类似模式。我将对统一容器进行 100 次访问,因此正确使用模式看起来很重要。

即使是像这样完全有意义的博客,也没有显示您应该在应用程序中获得对原始容器实例的引用的深度。 http://blog.ploeh.dk/2010/09/29/TheRegisterResolveReleasePattern.aspx

我很欣赏任何关于解决问题的好方法的提示。

4

2 回答 2

3

那篇 codeproject 文章基于 MVC1 于 2010 年发布。MVC3 现在包含一个 IDependencyResolver 实现,以便更好地与 IoC 集成。对于带有 Unity 的 MVC3,您可以查看Unity.MVC3

如果你想避免构造函数注入,你总是可以将 Unity 注册为默认的 IServiceLocator:

ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(Container));
于 2012-12-01T00:00:32.430 回答
0

如果有人感兴趣,在谷歌搜索期间:我结束了使用自定义全局类。1 静态调用开始事情。其余的作为接口/适配器模式。示例注册 Unity 和企业库。并记录经过身份验证的日志请求的重要细节。 ...这只是部分摘录...用于说明目的

从 MVC 应用程序 Global.asax 调用

public class BosMasterWebApplication : System.Web.HttpApplication
{
    private bool IsBootStraped;

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        AuthConfig.RegisterAuth();

        IsBootStraped = false;

    }
    public override void Init()
    {
        base.Init();
        // handlers managed by ASP.Net during Forms authentication
        AuthenticateRequest += new EventHandler(AuthHandler);
        PostAuthenticateRequest += new EventHandler(PostAuthHandler);

    }
    public void AuthHandler(object sender, EventArgs e)
    {
        // if you need to setup anything
    }
    public void PostAuthHandler(object sender, EventArgs e)
    {
        // called several times during the authentication process
        if (!IsBootStraped)
              BosGlobal.HttpBootStrap(this);
        if (Request.IsAuthenticated)
        {
            // did   FormsAuthentication.SetAuthCookie  was executed if we get here, so set username
            BosGlobal.BGA.IBosCurrentState.CurrentUser.SetFromEnvironment();
        }

    }
}


/// <summary>
/// Central adapter management. Dont abuse this class
/// </summary>
public static class BosGlobal
{
   public static IBosGlobalAdpater BGA { get; private set; }
    // set up the adapter
    static BosGlobal()
    {
         BGA = new BosGlobalAdapter( );
    }
  public static void HttpBootStrap(HttpApplication httpApplication)
    {
        BGA.BootStrap(httpApplication);
    }
    public static void LocalBootStrap(string machineName)
    { // the LOCAL WPF bootstrap alternative... no http request exists.
      BGA.BootStrap(machineName);
      }
}


public class BosGlobalAdapter : IBosGlobalAdpater
{
    public static bool IsBootStrapped { get; private set; }

    /// Unity Container with key dependencies registered
    public IUnityContainer IUnityContainer { get; private set; } //IOC Container 
    //Adapters

    public IBosLogAdapter ILogAdapter { get; private set; }
    public IBosExceptionManagerAdapter ExceptionManagerAdapter { get; private set; }
   public BosGlobalAdapter()
    {
      IsBootStrapped = false;
      IUnityContainer = new UnityContainer();// one container per work process. managing and resolving dependencies
    }

   public void BootStrap(HttpApplication httpApplication )
    {

        IBosCurrentState = new BosCurrentState(httpApplication);
      BootStrapEnterpriseLibrary();
        BootStrapAdapters();
       IsBootStrapped = true;
   }



    private void BootStrapAdapters()
    {
        ILogAdapter = new BosLogAdapter(IUnityContainer.Resolve<LogWriter>());
        ExceptionManagerAdapter = new BosExceptionManagerAdapter(IUnityContainer.Resolve<ExceptionManager>());
    }

    private void BootStrapEnterpriseLibrary()
    {   // now we tell unity about the container manager inside EntLib.
        // we dont want 2 containers, so we tell UNity look after EntLib as well please
        IUnityContainer.AddNewExtension<EnterpriseLibraryCoreExtension>();
    }
于 2012-12-05T11:40:35.193 回答