傻瓜式使用AutoFac

定义一个接口:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 
 6 namespace AutoFacTest
 7 {
 8     public interface IAddressService
 9     {
10         string GetAddress(int contactNumber);
11     }
12 }

实现类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace AutoFacTest
{
    public class AddressService : IAddressService
    {
        public string GetAddress(int contactNumber)
        {
            string result = string.Empty;

            if (contactNumber == 123)
                result = "上海浦东";

            return result;
        }
    }
}

先来定义一个容器:

 1 using Autofac;
 2 using Autofac.Core;
 3 using Autofac.Integration.Mvc;
 4 using Autofac.Extras.AggregateService;
 5 using System;
 6 using System.Collections.Generic;
 7 using System.Linq;
 8 using System.Web;
 9 
10 namespace AutoFacTest.Common
11 {
12     public class ObjectContainer
13     {
14         public static IContainer Container
15         {
16             get
17             {
18                 return _container;
19             }
20         }
21 
22         private static IContainer _container;
23 
24         private ObjectContainer()
25         {
26         }
27 
28         public static void Initialize(Action<ContainerBuilder> action)
29         {
30             var builder = new ContainerBuilder();
31 
32             if (action != null)
33             {
34                 action(builder);
35             }
36 
37             _container = builder.Build();
38         }
39 
40         public static bool IsRegistered<TService>()
41         {
42             ThrowIfNotInitialized();
43             return _container.IsRegistered<TService>();
44         }
45 
46         public static bool IsRegistered(Type serviceType)
47         {
48             ThrowIfNotInitialized();
49             return _container.IsRegistered(serviceType);
50         }
51 
52         public static TService Resolve<TService>(params Parameter[] parameters)
53         {
54             ThrowIfNotInitialized();
55             return _container.Resolve<TService>(parameters);
56         }
57 
58         public static object Resolve(Type serviceType, params Parameter[] parameters)
59         {
60             ThrowIfNotInitialized();
61             return _container.Resolve(serviceType, parameters);
62         }
63 
64         public static TService ResolveNamed<TService>(string serviceName, params Parameter[] parameters)
65         {
66             ThrowIfNotInitialized();
67             return _container.ResolveNamed<TService>(serviceName, parameters);
68         }
69 
70         public static object ResolveNamed(string serviceName, Type serviceType, params Parameter[] parameters)
71         {
72             ThrowIfNotInitialized();
73             return _container.ResolveNamed(serviceName, serviceType, parameters);
74         }
75 
76         public static bool TryResolve<TService>(out TService service)
77         {
78             ThrowIfNotInitialized();
79             return _container.TryResolve<TService>(out service);
80         }
81 
82         public static bool TryResolve(Type serviceType, out object service)
83         {
84             ThrowIfNotInitialized();
85             return _container.TryResolve(serviceType, out service);
86         }
87 
88         private static void ThrowIfNotInitialized()
89         {
90             if (_container == null)
91                 throw new InvalidOperationException("Container should be initialized before using it.");
92         }
93     }
94 }

Global中注册AddressService和IAddressService的依赖关系,自动将实现类AddressService注入到Ioc容器中。

using AutoFacTest.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Security;
using System.Web.SessionState;
using Autofac;
using Autofac.Integration.Mvc;
using Autofac.Extras.AggregateService;

namespace AutoFacTest
{
    public class Global : HttpApplication
    {
        private System.ComponentModel.IContainer components = null;
        protected void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            RegisterDependencies();
        }

        private void RegisterDependencies()
        {
            ObjectContainer.Initialize(builder =>
            {
                builder.RegisterType<AddressService>().As<IAddressService>().InstancePerDependency();
            });
        }
    }
}

使用:

1  IAddressService svc = Common.ObjectContainer.Resolve<IAddressService>();
2             string address = svc.GetAddress(123);

再也不用手动new那么多 object。再也不用手写factory,AutoFac就是这么方便。

posted @ 2017-04-20 15:41  ~扎克伯格  阅读(3775)  评论(4编辑  收藏  举报