AutoFac在Asp.net MVC中使用

使用工具:VS2015 基于.NET fromwork4.6.1

1.创建ASP.NET Web 应用程序

 

 

 

 2.选择一个空结构的MVC项目

 

 

 3.项目结构:

 

 

 4.创建控制器 和 视图

 

 

 5.新建两个类库项目IServices/IBll  一个用来声明接口,一个用来实现

 

 

 

ISerivces:

 public interface ISqlHelper
    {

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sql"></param>
        /// <returns>sql</returns>
        string SeaechSql(string sql);
        /// <summary>
        /// 执行
        /// </summary>
        /// <param name="sql"></param>
        /// <returns>影响行数</returns>
        int ExecSql(string sql);
    }

 public interface IFtpHelper
    {
        bool SendFile(string path);
        bool DownFile(string path);
    }

IBll:

 public class OracleHepler : ISqlHelper
    {
        public int ExecSql(string sql)
        {
            //SQL
            return new Random().Next(2);
        }

        public string SeaechSql(string sql)
        {
            //SQL
            return sql;
        }
    }
public class FtpHelper : IFtpHelper
    {
        /// <summary>
        /// 文件路径验证
        /// </summary>
        private Regex regex =  new  Regex(@"^[a-zA-Z]:((\\+[^\/:*?""<>|]+)+)\s*$");

        public bool DownFile(string path)
        {                     
            if (regex.IsMatch(path))
            {
                Console.WriteLine($"下载成功:路径{path}");
                return true;                      
            }
            Console.WriteLine($"格式错误:路径{path}");
            return false;
        }

        public bool SendFile(string path)
        {
            if (regex.IsMatch(path))
            {
                Console.WriteLine($"传输成功:路径{path}");
                return true;
            }
            Console.WriteLine($"格式错误:路径{path}");
            return false;
        }
    }

在MVC项目中配置AutoFac:

Global:

 public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            var build = new ContainerBuilder(); //构建容器
            build.RegisterControllers(typeof(MvcApplication).Assembly).PropertiesAutowired(); //依赖注入当前应用程序下的所有Controller

            Assembly asm = Assembly.Load("IBll");  //加载 IBLL下应用程序集
            build.RegisterAssemblyTypes(asm).Where(t => !t.IsAbstract).AsImplementedInterfaces().PropertiesAutowired();  //依赖注入IBLL下所有非抽象类的接口实现类

            var container = build.Build(); //构建
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); //全局注册使用设置
        }
    }

Control:

 public class DefaultController : Controller
    {
        public IFtpHelper ftp { get; set; }
        // GET: Default
        public ActionResult Index()
        {
            bool bl= ftp.DownFile("ftp://loaclhost:5000/ftp/1.txt");
            return Content(bl.ToString());
        }
    }

 

运行结果:

 

 

 

 

 

 在非Controller类中使用AutoFac:【DependencyResolver.Current.GetService<ISqlHelper>();】

1.添加类Tools

 public class Tools
    {

      public static int Test()
      {
        ISqlHelper help = DependencyResolver.Current.GetService<ISqlHelper>();
        return help.ExecSql("update table set x=y where a=b");
      }

    }

在Controller中去调用Tool. Test

 public class DefaultController : Controller
    {
        public IFtpHelper ftp { get; set; }
        // GET: Default
        public ActionResult Index()
        {
           /* bool bl = ftp.DownFile("ftp://loaclhost:5000/ftp/1.txt"); */

            return Content(Tools.Test().ToString());
        }
    }

 

执行结果

 

 

在子线程中使用AutoFac

PM=> install-package quartz -version 2.6.1

 

 新建 MyJob 定时类

下图为错误用法,无法使用

 

 

 

 

 

 

 

 

 Golbal中配置计划和定时

 public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            var build = new ContainerBuilder();
            build.RegisterControllers(typeof(MvcApplication).Assembly).PropertiesAutowired();

            Assembly asm = Assembly.Load("IBll");
            build.RegisterAssemblyTypes(asm).Where(t => !t.IsAbstract).AsImplementedInterfaces().PropertiesAutowired();

            var container = build.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            {
                IScheduler scheduler;
                //调度器工厂
                ISchedulerFactory factory;

                //创建一个调度器
                factory = new StdSchedulerFactory();
                scheduler = factory.GetScheduler();
                scheduler.Start();
                //2、创建一个任务
                IJobDetail job = JobBuilder.Create<MyJob>().WithIdentity("job1", "group1").Build();

                //3、创建一个触发器
                //DateTimeOffset runTime = DateBuilder.EvenMinuteDate(DateTimeOffset.UtcNow);
                ITrigger trigger = TriggerBuilder.Create()
                    .WithIdentity("trigger1", "group1")
                    .WithCronSchedule("0/5 * * * * ?")     //5秒执行一次
                                                           //.StartAt(runTime)
                    .Build();

                //4、将任务与触发器添加到调度器中  
                scheduler.ScheduleJob(job, trigger);
                //5、开始执行
                scheduler.Start();
            }
        }
    }

调式看结果:

 

 

 正确使用MyJob中使用:

    public class MyJob : IJob
    {
        public void Execute(IJobExecutionContext context)
        {
            try
            {       
                ISqlHelper sql;
                var container = AutofacDependencyResolver.Current.ApplicationContainer;
                using (container.BeginLifetimeScope())
                {
                    sql = container.Resolve<ISqlHelper>();
                    string s = sql.SeaechSql("SELECT *FROM TABLENAME");
                    File.WriteAllText($"../App_Data/{DateTime.Now.ToString("yyyyMMddHHmissfff")}.txt", s);
                }                                                                                                                       
            }
            catch (System.Exception e)
            {
                File.WriteAllText($"{HostingEnvironment.MapPath("~/")}/App_Data/{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.txt", e.Message);
            }
            
        }
    }

 

posted @ 2021-04-27 14:05  后跳  阅读(144)  评论(0编辑  收藏  举报