c#使用AutoFac实现动态注入

上文大概介绍了使用AutoFac实现依赖注入.今天写着写着,觉得每次都要写类似于builder.RegisterType<UserService>().As<IUserService>();的代码很烦.于是翻资料实现了一个帮助类.来动态的实现注入.下面贴出代码.

using Autofac;
using System;
using System.Linq;
namespace MVCBlog.Web.CommonHelper
{
    public class ResolverHelper
    {
        public static object GetResolver<TService>()
        {
            var iTypes = typeof(TService).GetInterfaces();
            if(iTypes.Count()==0)
            {
                throw new NotImplementedException("依赖注入的类型没有实现接口");
            }
            Type iType = iTypes[0];
            if ( ApplicationContainer.Container.IsRegistered(iType))
            {
                return ApplicationContainer.Container.Resolve(iType);
            }

            var builder = new ContainerBuilder();

            RegisterServices<TService>(builder, iType);
            builder.Update(ApplicationContainer.Container);
            return ApplicationContainer.Container.Resolve(iType);
        }
        private static void RegisterServices<TService>(ContainerBuilder builder,Type iType)
        {
            builder.RegisterType<TService>().As(new Type[] { iType });
        }
    }
}

ApplicationContainer类:

using Autofac;

namespace MVCBlog.Web.CommonHelper
{
    public class ApplicationContainer
    {
        public static IContainer Container { get; set; }
    }
}

这样子调用的话就可以这样ResolverHelper.GetResolver<MVCBlog.Service.PostService>();

c#使用AutoFac实现动态注入》上有2条评论

发表评论

电子邮件地址不会被公开。 必填项已用*标注