ioc autofac简单示例

1.winform用法:

nuget安装autofac

public interface ILog
    {
        bool Log(string msg);
    }
    public class TXTLogger : ILog
    {
        public bool Log(string msg)
        {
            Console.WriteLine(msg + " saved in file log.log");
            return true;
        }
    }
    public class DBLogger : ILog
    {
        public bool Log(string msg)
        {
            Console.WriteLine(msg + " saved in mssqlserver");
            return true;
        }
    }

    public class UserService
    {
        public ILog log;
        public UserService(ILog ilog) //构造函数注入
        {
            log = ilog;
        }

        public bool AddUser()
        {
            log.Log("insert user succeed ,userId is :1");
            return true;
        }
    }
     Autofac.IContainer container;

        private void Form1_Load(object sender, EventArgs e)
        {//注册
            ContainerBuilder builder = new ContainerBuilder();
            builder.RegisterType<DBLogger>().As<ILog>();
            builder.RegisterType<TXTLogger>().As<ILog>();//后注册的会覆盖之前注册的
            builder.RegisterType<UserService>();
            container = builder.Build();


            Test();
    }
      
  void Test()
        {

var service = container.Resolve<UserService>(); //解析;并没有实例化new UserService也没有传入构造函数参数,autofac自动注入了
if (service!=null)
{
    var result = service.AddUser(); //输出insert user succeed ,userId is :1 saved in file log.log
}


        }

 

2.mvc用法:

安装 autofac和autofac.mvc5:

global.asax.cs中

protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);


       //mvc注册  参考:http://www.w2*bc.com/article/180590
            ContainerBuilder builder = new ContainerBuilder();
           
            builder.RegisterControllers(Assembly.GetExecutingAssembly()).AsSelf().PropertiesAutowired();
            builder.RegisterType<DBLogger>().As<ILog>().InstancePerLifetimeScope();
            builder.RegisterType<TXTLogger>().As<ILog>().InstancePerLifetimeScope();//后注册的会覆盖之前注册的
            builder.RegisterType<UserService>().InstancePerLifetimeScope();
            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));


//webapi注册
//WebApi Register
//builder.RegisterApiControllers(Assembly.GetExecutingAssembly()).AsSelf().PropertiesAutowired();
//builder.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration);
/builder.RegisterWebApiModelBinderProvider();
}

 

controller中调用Test方法 

        public static void Test()
        {
            //var log = DependencyResolver.Current.GetService<ILog>();
            //var result = log.Log("test msg");

            var service = DependencyResolver.Current.GetService<UserService>();
            if (service != null)
            {
                service.AddUser(); //输出insert user succeed ,userId is :1 saved in file log.log
            }

        }

 

参考:http://www.cnblogs.com/hkncd/archive/2012/11/21/2780041.html

 参考:http://www.w2b*c.com/article/180590

 

3.属性注入:

public class AA
    {
        public BB bb;
        public AA()
        {
        }

        public void TestAA()
        {
            bb.TestBB();
        }
    }
    public class BB
    {
        public void TestBB()
        {
            Console.WriteLine("TestBB Executed!");
        }
    }
       

       ContainerBuilder builder = new ContainerBuilder(); builder.RegisterType<BB>(); builder.Register(c => new AA() { bb = c.Resolve<BB>() }); //属性注入 var container = builder.Build();
var a = container.Resolve<AA>(); a.TestAA(); //输出:TestBB Executed!

 

 

From:http://www.cnblogs.com/xuejianxiyang/p/7064974.html

posted @ 2017-06-22 14:51  Ace001  阅读(662)  评论(3编辑  收藏  举报