Autofac的简单封装

将Autofac集成到自己的框架项目中,对Autofac进行了简单的封装,方便调用。


public class IocHelper
{
private static IContainer _Container;

    public static IContainer Container
    {
        get 
        {
            if (_Container == null)
            {
                _Container = _Build.Build();
            }
            return _Container; 
        }
    }


    private static ContainerBuilder _Build ;

    public static ContainerBuilder CurrentBuild
    {
        get 
        { 
            return _Build;
        }
    }

    static IocHelper()
    {
        _Build = new ContainerBuilder();
    }

    public static void Register()
    {
        _Build.RegisterType();
    }

    public static void Register()
    {
        _Build.RegisterType().As();
    }

    public static void Register(object obj)
    {
        _Build.RegisterInstance(obj);
    }

    public static void RegisterAssembly(Assembly assembly)
    {
        _Build.RegisterAssemblyTypes(assembly);
    }

    public static void RegisterAssemblys(Assembly[] Assemblys)
    {
        _Build.RegisterAssemblyTypes(Assemblys);
    }

    public static T Resolve(string name)
    {
        return Container.ResolveNamed(name);
    }

    public static T Resolve()
    {
        return Container.Resolve();
    }
}

调用方法如下


IocHelper.Register();

        IocHelper.RegisterAssembly(Assembly.GetExecutingAssembly());

        IClassA ca = IocHelper.Resolve();
        ClassB cb = IocHelper.Resolve();

你可能感兴趣的:(Autofac的简单封装)