Asp.net WebAPI Ioc

网上关于webapi Ioc 的东西很多,如http://efmvc.codeplex.com/SourceControl/latest#MyFinance.Web/Global.asax.cs 这是用微软IUnityContainer。还有:

ASP.NET Web API和依赖注入

但是网上关于Autofac 确是很少, 我第一次接触也是单元测试的时候 ASP.NET Web API Unit Testing 

这里就简单贴点code吧: 

 public class Startup
    {
        public void Configuration(Owin.IAppBuilder appBuilder)
        {
            var config = new HttpConfiguration();
            config.MessageHandlers.Add(new HeaderAppenderHandler());
            config.MessageHandlers.Add(new EndRequestHandler());
            config.Filters.Add(new ArticlesReversedFilter());
            config.Services.Replace(typeof(IAssembliesResolver), new CustomAssembliesResolver());

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            config.MapHttpAttributeRoutes();

            // Autofac configuration
            var builder = new ContainerBuilder();
            builder.RegisterApiControllers(typeof(ArticlesController).Assembly);
            //builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
            //      .Where(t =>!t.IsAbstract && typeof(ApiController).IsAssignableFrom(t));
            // Unit of Work
            var _unitOfWork = new Mock<IUnitOfWork>();
            builder.RegisterInstance(_unitOfWork.Object).As<IUnitOfWork>();

            //Repositories
            var _articlesRepository = new Mock<IArticleRepository>();
            _articlesRepository.Setup(x => x.GetAll()).Returns(
                    BloggerInitializer.GetAllArticles()
                );
            builder.RegisterInstance(_articlesRepository.Object).As<IArticleRepository>();

            var _blogsRepository = new Mock<IBlogRepository>();
            _blogsRepository.Setup(x => x.GetAll()).Returns(
                BloggerInitializer.GetBlogs
                );
            builder.RegisterInstance(_blogsRepository.Object).As<IBlogRepository>();

            // Services
            builder.RegisterAssemblyTypes(typeof(ArticleService).Assembly)
               .Where(t => t.Name.EndsWith("Service"))
               .AsImplementedInterfaces().InstancePerRequest();

            builder.RegisterInstance(new ArticleService(_articlesRepository.Object, _unitOfWork.Object));
            builder.RegisterInstance(new BlogService(_blogsRepository.Object, _unitOfWork.Object));

            IContainer container = builder.Build();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            appBuilder.UseWebApi(config);
        }
    }

我这里是单元测试, 所以安装包如下:

<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EntityFramework" version="6.1.3" targetFramework="net45" />
  <package id="Autofac" version="3.5.0" targetFramework="net45" />
  <package id="Autofac.WebApi2" version="3.4.0" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.Core" version="5.2.3" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.Owin" version="5.2.3" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.SelfHost" version="5.2.3" targetFramework="net45" />
  <package id="Microsoft.Owin" version="3.0.1" targetFramework="net45" />
  <package id="Microsoft.Owin.Host.HttpListener" version="3.0.1" targetFramework="net46" />
  <package id="Microsoft.Owin.Hosting" version="3.0.1" targetFramework="net46" />
  <package id="Owin" version="1.0" targetFramework="net45" />
  <package id="Moq" version="4.2.1510.2205" targetFramework="net45" />
  <package id="Newtonsoft.Json" version="6.0.4" targetFramework="net45" />
  <package id="NUnit" version="3.2.0" targetFramework="net45" />
  <package id="NUnitTestAdapter" version="2.0.0" targetFramework="net45" />
 
</packages>

 测试的时候建议使用 TestDriven.NET

你可能感兴趣的:(Asp.net WebAPI Ioc)