C# Autofac依赖注入

C# Unity依赖注入   **
1、依赖注入方式
      注册程序集中所有类
      单个注册
      构造器注入()
      属性注入()
      方法调用注入()

2、管理 NuGet 程序包
      添加 Autofac 、Autofac.Configuration 的引用【】
      添加 Autofac 、Autofac.Extensions.DependencyInjection 的引用【.NET Core

      如果是 Web 项目就下载这个AutoFac
      如果是 MVC 项目则下载 AutoFac.Mvc5(还有说搜索Autofac ASP.NET MVC 5 Integration)

      新建类库Auto.Repository、Auto.Service

3、VersionRepository.cs类代码如下

using System;

namespace Auto.Repository
{
    public interface IVersionRepository
    {
        string GetVersion(string code);
    }

    public class VersionRepository : IVersionRepository
    {
        public string GetVersion(string code)
        {
            return $"{DateTime.Now.ToString("yyyy-MM-dd")}-{code}";
        }
    }
}

4、People.cs类代码如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Auto.Repository
{
    public interface IPeople
    {
        string GetPeople();
    }

    public class People : IPeople
    {
        public string GetPeople()
        {
            return "张三 男 歌手";
        }
    }
}

5、Web项目中 -> App_Start文件夹 -> 新建“AutofacConfig”类

using Auto.Repository;
using Autofac;
using Autofac.Integration.Mvc;
using System.Linq;
using System.Reflection;
using System.Web.Compilation;

namespace Web
{
    public class AutofacConfig
    {
        public static void RegisterAutofac()
        {
            var builder = new ContainerBuilder();

            //对程序集中所有的Controller一次性的完成注册
            builder.RegisterControllers(Assembly.GetExecutingAssembly());//注册mvc容器的实现

            //单个类注册到容器
            builder.RegisterType<People>().As<IPeople>();

            var assemblys = BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToList();

            builder.RegisterAssemblyTypes(assemblys.ToArray())
                .Where(t => t.Name.EndsWith("Repository"))//查找程序集中以Repository结尾的类型
                .AsImplementedInterfaces();//将找到的类和对应的接口放入IOC容器

            builder.RegisterAssemblyTypes(assemblys.ToArray())
                .Where(t => t.Name.EndsWith("Service"))//查找程序集中以Repository结尾的类型
                .AsImplementedInterfaces();//表示注册的类型,以接口的方式注册

            var dal = Assembly.Load("***.Edu.Repository");
            var dbContext = dal.GetTypes().FirstOrDefault(f => f.Name == "***DbContext");
            builder.RegisterType(dbContext).InstancePerRequest().As(dbContext);

            //使用单例模式
            builder.RegisterType<RedisCacheManager>()
                .As<ICacheManager>()
                .SingleInstance()
                .PropertiesAutowired();


            var container = builder.Build(); //创建一个容器
            //config.DependencyResolver = new AutofacDependencyResolver(container);//注册api容器需要使用HttpConfiguration对象
            System.Web.Mvc.DependencyResolver.SetResolver(new AutofacDependencyResolver(container));//注册MVC容器
        }
    }
}

6、Global.asax.cs类protected void Application_Start()方法中调用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace Web
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            AutofacConfig.RegisterAutofac();
        }
    }
}

7、Controller调用

using Auto.Repository;
using System.Web.Mvc;

namespace Web.Controllers
{
    public class DefaultController : Controller
    {
        private IVersionRepository _versionSvc;
        private IPeople _people;

        public DefaultController(IVersionRepository versionService, IPeople people)
        {
            _versionSvc = versionService;
            _people = people;
        }

        public ActionResult Index()
        {
            string v = _versionSvc.GetVersion("1");
            string p = _people.GetPeople();
            return View();
        }
    }
}

1、AutofacLifetimeScope 注入

public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
    var scope = context.OwinContext.GetAutofacLifetimeScope();
    var clientRepo = scope.Resolve<IClientRepository>();

    var autofacLifetimeScope = OwinContextExtensions.GetAutofacLifetimeScope(context.OwinContext);
    var userService = autofacLifetimeScope.Resolve<IClientRepository>();    
}

单个注册
构造器注入()
属性注入()
方法调用注入()
*

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值