如何正确的基本MVC5.1网站上注册AutoFac? [英] How do I properly register AutoFac in a basic MVC5.1 website?

查看:437
本文介绍了如何正确的基本MVC5.1网站上注册AutoFac?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

AutoFac最近已经更新了MVC 5.1,但在写作的时候,我发现,文档缺乏(尤其是对于一个简单的例子)。

AutoFac has recently been updated for MVC 5.1 but at the time of writing I find that the documentation is lacking (especially for a simple example).

我想注入依赖到MVC控制器并注册自己为实现例如电子邮件(发送实际打印VS输出窗口)作为一个基本的例子。

I would like to inject dependencies into MVC Controllers and register my own implementations for e.g. e-mail (actual sending vs print to output window) as a basic example.

我不知道是否我缺少这一个很好的资源,我略有担心,因为它使用的实施可能对MVC5.1不同的OWIN规范(ASP.NET身份使用OWIN并有一些用于正确实例OWIN),所以需要检查,我把事情的特殊属性的权利。

I'm do not know if I am missing a good resource for this and I am slight concerned that because it uses the OWIN specification that the implementation may differ for MVC5.1 (ASP.NET Identity uses OWIN and there is some special attributes used to properly instantiate OWIN) so need to check I am getting things right.

我有以下设置code工作的例子 - 是一个标准的MVC5.1 web应用程序这是正确的和好的做法

奖金的问题:我需要InstancePerHtt prequest添加到RegisterControllers行?
即builder.RegisterControllers(typeof运算(MvcApplication).Assembly).InstancePerHtt prequest();

Bonus question: do I need to add InstancePerHttpRequest to the RegisterControllers line? i.e. builder.RegisterControllers(typeof(MvcApplication).Assembly).InstancePerHttpRequest();

(注:我看到Autofac在GitHub上的例子,但找不到合适的MVC5.1例如纯)

(Note: I see the examples on GitHub from Autofac but cannot find an plain example appropriate to MVC5.1.)

public static void RegisterDependencies()
{
    // Register MVC-related dependencies
    var builder = new ContainerBuilder();
    builder.RegisterControllers(typeof(MvcApplication).Assembly);
    builder.RegisterModelBinders(typeof(MvcApplication).Assembly);
    builder.RegisterModule<AutofacWebTypesModule>();

    // Register e-mail service
    builder.RegisterType<EmailSenderToDebug>().As<IEmailSender>().InstancePerHttpRequest();

    builder.RegisterModelBinderProvider();

    // Set the MVC dependency resolver to use Autofac
    var container = builder.Build();
    DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}

和我的控制器:

public class HomeController : Controller
{

    public IEmailSender _email { get; set; }

    public  HomeController(IEmailSender es)
    {
        this._email = es;
    }
    //
    // GET: /Home/
    public ActionResult Index()
    {

        Email e = new Email();
        e.To(new MailAddress("something@something.com", "mr. something"));
        e.Subject("test");
        e.Message("hello world");
        e.From(new MailAddress("somethingElse@somethingElse.com", "mr. else"));
        this._email.SendEmail(e);
        return View();
    }
}

谢谢!

推荐答案

下面就是我 - 反馈欢迎!

Here's what I have - feedback welcome!

的Global.asax.cs:

Global.asax.cs:

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        // Register Inversion of Control dependencies
        IoCConfig.RegisterDependencies();

        // Typical MVC setup
        // ....
    }
}

App_Start文件夹:

App_Start folder:

public class IoCConfig
{

    /// <summary>
    /// For more info see 
    /// :https://code.google.com/p/autofac/wiki/MvcIntegration (mvc4 instructions)
    /// </summary>
    public static void RegisterDependencies()
    {
        #region Create the builder
        var builder = new ContainerBuilder();
        #endregion

        #region Setup a common pattern
        // placed here before RegisterControllers as last one wins
        builder.RegisterAssemblyTypes()
               .Where(t => t.Name.EndsWith("Repository"))
               .AsImplementedInterfaces()
               .InstancePerHttpRequest();
        builder.RegisterAssemblyTypes()
               .Where(t => t.Name.EndsWith("Service"))
               .AsImplementedInterfaces()
               .InstancePerHttpRequest();
        #endregion

        #region Register all controllers for the assembly
        // Note that ASP.NET MVC requests controllers by their concrete types, 
        // so registering them As<IController>() is incorrect. 
        // Also, if you register controllers manually and choose to specify 
        // lifetimes, you must register them as InstancePerDependency() or 
        // InstancePerHttpRequest() - ASP.NET MVC will throw an exception if 
        // you try to reuse a controller instance for multiple requests. 
        builder.RegisterControllers(typeof(MvcApplication).Assembly)
               .InstancePerHttpRequest();

        #endregion

        #region Register modules
        builder.RegisterAssemblyModules(typeof(MvcApplication).Assembly);
        #endregion

        #region Model binder providers - excluded - not sure if need
        //builder.RegisterModelBinders(Assembly.GetExecutingAssembly());
        //builder.RegisterModelBinderProvider();
        #endregion

        #region Inject HTTP Abstractions
        /*
         The MVC Integration includes an Autofac module that will add HTTP request 
         lifetime scoped registrations for the HTTP abstraction classes. The 
         following abstract classes are included: 
        -- HttpContextBase 
        -- HttpRequestBase 
        -- HttpResponseBase 
        -- HttpServerUtilityBase 
        -- HttpSessionStateBase 
        -- HttpApplicationStateBase 
        -- HttpBrowserCapabilitiesBase 
        -- HttpCachePolicyBase 
        -- VirtualPathProvider 

        To use these abstractions add the AutofacWebTypesModule to the container 
        using the standard RegisterModule method. 
        */
        builder.RegisterModule<AutofacWebTypesModule>();

        #endregion

        #region Set the MVC dependency resolver to use Autofac
        var container = builder.Build();
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        #endregion

    }

 }

那么,您认为合适它是真正伟大的,如果你有一个模块化的应用程序,你不知道你要什么项目,包括你可以注册模块。您可以设置的NuGet项目及无需人工干预(我希望!)......

Then you can register modules as you see fit which is really great if you have a modularised application and you don't know what you are going to include in your project. You can nuget setup your project and no manual intervention required (I wish!)....

public class RegisterApplicationIoC : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterType<EmailSenderToDebug>()
               .As<IEmailSender>()
               .InstancePerHttpRequest();
    }
}

这篇关于如何正确的基本MVC5.1网站上注册AutoFac?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆