老程序员跪求 Autofac与ASP.NET Areas工程问题
最近有个ASP.NET项目,工程类型为ASP.NET + MVC + WebApi2.2 + OWIN,希望引入Autofac这个Ioc框架。网上查了两三天,无解。现求助于各位高手。
相关代码见后。问题描述:
问题1:
当”备注2“代码使能语句
时,Areas中的AbcController构造参数可通过Atutofac注入,但HomeAreaRegistration中的路由设置失效。即,对于AbcController,只能通过链接
http://localhost:1607/api/abc/gettest访问,而不是http://localhost:1607/api/home/abc/gettest。
当把备注1代码切换成
var config = GlobalConfiguration.Configuration;
时,AbcController构造参数也可通过Atutofac注入,但HomeAreaRegistration中的路由设置有效,即只能通过http://localhost:1607/api/home/abc/gettest访问。但是,不能通过http://localhost:1607/Account/Login链接访问继承至Controller的AccountController(备注0)的Login方法——而先前的方式是正常的。
概括起来,HttpConfiguration不管是通过new HttpConfiguration新建一个,还是使用GlobalConfiguration.Configuration这个全局,都有各自问题。
问题2:
只要启用了Autofac,在ApiController中,HttpContext.Current.Session恒为null(注意,我已在Global文件中覆写了Init方法)。
以上,何解?
都说Autofac名气大,但不管国内还是国外的相关示例代码,没有一个是Areas工程的,到底支不支持Areas,真是郁闷。
==========================================================
相关代码:
web.config代码片段:
Global.asax.cs:
Startup.cs:
AutofacConfig.cs:
Areas/HomeAreaRegistration.cs:
Areas/Home/AbcController.cs
AccountController.cs:
相关代码见后。问题描述:
问题1:
当”备注2“代码使能语句
var config = new HttpConfiguration();
时,Areas中的AbcController构造参数可通过Atutofac注入,但HomeAreaRegistration中的路由设置失效。即,对于AbcController,只能通过链接
http://localhost:1607/api/abc/gettest访问,而不是http://localhost:1607/api/home/abc/gettest。
当把备注1代码切换成
var config = GlobalConfiguration.Configuration;
时,AbcController构造参数也可通过Atutofac注入,但HomeAreaRegistration中的路由设置有效,即只能通过http://localhost:1607/api/home/abc/gettest访问。但是,不能通过http://localhost:1607/Account/Login链接访问继承至Controller的AccountController(备注0)的Login方法——而先前的方式是正常的。
概括起来,HttpConfiguration不管是通过new HttpConfiguration新建一个,还是使用GlobalConfiguration.Configuration这个全局,都有各自问题。
问题2:
只要启用了Autofac,在ApiController中,HttpContext.Current.Session恒为null(注意,我已在Global文件中覆写了Init方法)。
以上,何解?
都说Autofac名气大,但不管国内还是国外的相关示例代码,没有一个是Areas工程的,到底支不支持Areas,真是郁闷。
==========================================================
相关代码:
web.config代码片段:
<system.web>
<authentication mode="Forms">
//****备注0
<forms loginUrl="~/Account/Login" timeout="2880" slidingExpiration="true" name=".STSASPAUTH" />
<!--<forms loginUrl="~/Home/Account2/Login" timeout="2880" slidingExpiration="true" name=".STSASPAUTH" />-->
</authentication>
<authorization>
<deny users="?" />
</authorization>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
</system.web>
Global.asax.cs:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
// eliminate this line code to let OWIN manage WebApi.
//GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
public override void Init() //******备注1
{
PostAuthenticateRequest += MvcApplication_PostAuthenticateRequest;
base.Init();
}
private void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
{
HttpContext.Current.SetSessionStateBehavior(
SessionStateBehavior.Required);
}
// .....
}
Startup.cs:
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
AutofacConfig.Config(app);
ConfigureAuth(app);
}
}
AutofacConfig.cs:
class AutofacConfig
{
public static IContainer Container
{
get; private set;
}
public static void Config(IAppBuilder app)
{
var builder = new ContainerBuilder();
//...
builder.RegisterType<ApplicationDbContext>().AsSelf().As<DbContext>().InstancePerRequest();
//builder.RegisterType<ApplicationUserManager>().InstancePerRequest();
builder.Register<ApplicationUserManager>(
c => ApplicationUserManager.Create2(c.Resolve<IUserStore<UserEntity>>())).InstancePerRequest();
builder.RegisterType<UserStore<UserEntity>>().As<IUserStore<UserEntity>>();
// Get your HttpConfiguration. In OWIN, you'll create one
// rather than using GlobalConfiguration.
var config = new HttpConfiguration(); ///******************备注2*******************
//var config = GlobalConfiguration.Configuration;
// don't forget this line
//AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(config);
// for MVC ...
#region
// Register your MVC controllers.
builder.RegisterControllers(typeof(MvcApplication).Assembly);
// Run other optional steps, like registering model binders,
// web abstractions, etc., then set the dependency resolver
// to be Autofac.
// OPTIONAL: Register model binders that require DI.
builder.RegisterModelBinders(Assembly.GetExecutingAssembly());
builder.RegisterModelBinderProvider();
// OPTIONAL: Register web abstractions like HttpContextBase.
builder.RegisterModule<AutofacWebTypesModule>();
// OPTIONAL: Enable property injection in view pages.
builder.RegisterSource(new ViewRegistrationSource());
// OPTIONAL: Enable property injection into action filters.
builder.RegisterFilterProvider();
// OPTIONAL: Enable action method parameter injection (RARE).
//builder.InjectActionInvoker();
#endregion
// for WebApi2 ...
#region
// Register your Web API controllers.
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
// OPTIONAL: Register the Autofac filter provider.
builder.RegisterWebApiFilterProvider(config);
#endregion
var container = builder.Build();
Container = container;
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
// OWIN MVC and WebApi2 SETUP ...
// Register the Autofac middleware FIRST, then the Autofac Web API middleware,
// and finally the standard Web API middleware.
app.UseAutofacMiddleware(container);
app.UseAutofacMvc();
app.UseAutofacWebApi(config);
app.UseWebApi(config);
}
}
Areas/HomeAreaRegistration.cs:
public class HomeAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Home";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.Routes.MapHttpRoute(
name: "Home_WebApiRout",
routeTemplate: "api/Home/{controller}/{action}/{id}",
defaults: new { action = "Index", id = RouteParameter.Optional }
);
context.MapRoute(
"Home_default",
"Home/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
}Areas/Home/AbcController.cs
public class AbcController : ApiController
{
private ApplicationSignInManager _signInManager;
private ApplicationUserManager _userManager;
private ICultureService _cultureSvc;
private IUserService _userSvc;
private ILogService _logSvc;
public AbcController(ICultureService cultureSvc, IUserService userSvc, ILogService logSvc)
{
_cultureSvc = cultureSvc;
_userSvc = userSvc;
_logSvc = logSvc;
}
[AllowAnonymous]
[HttpGet]
public IHttpActionResult GetTest()
{
var s = HttpContext.Current.Session;
return Ok();
}
}AccountController.cs:
public class AccountController : Controller
{
// ...
public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager,
ICultureService cultureSvc, IUserService userSvc, ILogService logSvc)
{
UserManager = userManager;
SignInManager = signInManager;
_cultureSvc = cultureSvc;
_userSvc = userSvc;
_logSvc = logSvc;
}
//
// GET: /Account/Login
[AllowAnonymous]
public async Task<ActionResult> Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
await _cultureSvc.DeduceCultureNameAsync();
return View();
}
//...
}
...全文
相关推荐
asp.net mvc2 机试面试题
8. ** Areas**:对于大型项目,ASP.NET MVC2提供了Areas功能,可以将应用程序划分为逻辑上独立的部分。面试可能询问如何设置和使用Areas,以及它们如何帮助组织复杂的项目结构。
asp.net mvc5 源码
**八、 Areas与多项目结构**Areas功能使大型应用可以按功能划分为多个独立的模块,每个模块有自己的控制器、视图和模型,提高了代码组织和可维护性。
asp.net mvc 例子
. ** Areas and Controllers**:对于大型应用,可以使用Areas来组织控制器,每个Area可以视为一个小的独立应用,有助于保持代码结构清晰。9.
Apress - Pro ASP.NET MVC Framework
七、 Areas与大型项目组织对于大型项目,ASP.NET MVC引入了Areas概念,允许将应用程序划分为多个功能区域,每个区域有自己的模型、视图和控制器,从而更好地组织和管理代码。
ASP。NET与MVC5.rar_.net_ASP.NET MVC例子_ASP。NET与MVC5_MVC5_apsx
**路由系统**:ASP.NET MVC5使用路由系统来确定URL与控制器和操作方法的映射,使得URL更加友好和易于理解。2.


