demo20230512/App_Start/IoCConfig.cs
2023-05-12 10:20:28 +08:00

93 lines
3.6 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using Autofac;
using Autofac.Integration.Mvc;
using Autofac.Integration.WebApi;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity;
using Weee.DAL;
using Weee.Models;
using Weee.Service;
using Weee.Controllers;
using System.Reflection;
using Weee.Filter;
namespace Weee
{
public class IoCConfig
{
public static void RegisterDependencies()
{
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterControllers(typeof(MvcApplication).Assembly);
containerBuilder.RegisterApiControllers(typeof(MvcApplication).Assembly);
containerBuilder.RegisterModule(new AutofacWebTypesModule());
// to do registration module includes dependency injection bindings which is defined at the end of the post
containerBuilder.RegisterModule(new RegistrationModule());
containerBuilder.RegisterFilterProvider();
containerBuilder.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration);
var container = containerBuilder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
// DependencyResolver.SetResolver(new AutofacWebApiDependencyResolver(container));
}
}
public class RegistrationModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
//builder.RegisterType<UnitOfWork>()
// .As<IUnitOfWork>()
// .InstancePerLifetimeScope();
builder.RegisterType<WeeeDataContext>()
.AsSelf()
.InstancePerRequest();
builder.RegisterType<UserManager<User>>()
.AsSelf();
builder.Register(x => new UserStore<User>(x.Resolve<WeeeDataContext>()))
.As<IUserStore<User>>();
builder.Register(x => new UserStore<User>(x.Resolve<WeeeDataContext>()))
.AsSelf();
builder.RegisterType<MvcLogAttribute>().PropertiesAutowired();
builder.RegisterType<ApiLogAttribute>().PropertiesAutowired();
//builder.RegisterType<UserStore<User>>()
// .As<IUserStore<User>>();
//builder.RegisterType<WeeeDataService>()
// .AsSelf()
// .InstancePerRequest();
//builder.RegisterType<WeeeLCADataService>()
// .AsSelf()
// .InstancePerRequest();
//builder.RegisterType<WeeeMaterialDataService>()
// .AsSelf()
// .InstancePerRequest();
string @namespace = "Weee.Service";
var q = from t in Assembly.GetExecutingAssembly().GetTypes()
where t.IsClass && t.Namespace == @namespace
select t;
builder.RegisterTypes(q.ToArray())
.AsSelf()
.InstancePerRequest();
builder.RegisterType<Storage.AzureStorage>()
.SingleInstance();
builder.RegisterType<EmailService.Service>()
.SingleInstance();
//builder.RegisterType<WeeeDataContext>()
//.As<IWeeeDataContext>()
//.InstancePerRequest();
//builder.RegisterType<UserStore<User>>()
// .As<IUserStore<User>>();
}
}
}