// ***********************************************************************
// Assembly : OpenAuth.Mvc
// Author : yubaolee
// Created : 10-26-2015
//
// Last Modified By : yubaolee
// Last Modified On : 10-26-2015
// ***********************************************************************
//
// Copyright (c) www.cnblogs.com/yubaolee. All rights reserved.
//
// IOC扩展
// ***********************************************************************
using System.Reflection;
using System.Web.Http;
using System.Web.Mvc;
using Autofac;
using Autofac.Integration.Mvc;
using Autofac.Integration.WebApi;
using OpenAuth.App;
using OpenAuth.Domain.Interface;
using OpenAuth.Repository;
namespace OpenAuth.WebApi
{
internal static class AutofacExt
{
public static void InitAutofac()
{
var builder = new ContainerBuilder();
//注册数据库基础操作和工作单元
builder.RegisterGeneric(typeof(BaseRepository<>)).As(typeof(IRepository<>)).PropertiesAutowired();
builder.RegisterType(typeof (UnitWork)).As(typeof (IUnitWork)).PropertiesAutowired();
//注册app层
builder.RegisterAssemblyTypes(Assembly.GetAssembly(typeof (AuthorizeApp))).PropertiesAutowired();
// OPTIONAL: Register model binders that require DI.
builder.RegisterModelBinders(Assembly.GetExecutingAssembly());
builder.RegisterModelBinderProvider();
// OPTIONAL: Register web abstractions like HttpContextBase.
builder.RegisterModule();
// OPTIONAL: Enable property injection in view pages.
builder.RegisterSource(new ViewRegistrationSource());
// OPTIONAL: Enable property injection into action filters.
builder.RegisterFilterProvider();
//注册所有的ApiControllers
builder.RegisterApiControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
var container = builder.Build();
HttpConfiguration config = GlobalConfiguration.Configuration;
//注册api容器需要使用HttpConfiguration对象
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
///
/// 从容器中获取对象
///
///
public static T GetFromFac()
{
return (T)DependencyResolver.Current.GetService(typeof(T));
}
}
}