nopcommerce中文网

nopcommerce是国外asp.net领域一个高质量的b2c开源项目,基于EntityFramework和MVC开发,QQ群1:75272942(2000人超级群,已满) QQ群2:640322459

导航 - 搜索

Autofac怎么依赖注入静态方法

Autofac一般是通过Contrller的构造函数或者属性来注入,但是这有一个共同点就是调用这个类的方法一般都是实例方法,也就是要实例化这个类才能调用它的方法。但是如果它是一个静态方法我们又该怎么办呢?其实也很简单,下面我们就通过一个写日志的组件来介绍怎么实现ASP.NET MVC5类的静态方法的依赖注入。因为考虑到很多地方都要用到写日志这个方法,而且我们又不想每次调用都需要new一个对象,所以把调用方法封装成一些静态方法。

DependencyRegistrar.cs

  1. using Autofac;
  2. using Autofac.Integration.Mvc;
  3. using Lanhu.Services;
  4. using Lanhu.Services.MetionNowOrder;
  5. using Lanhu.Services.Member;
  6. using System.Web.Mvc;
  7. namespace Lanhu.Admin
  8. {
  9. public class DependencyRegistrar
  10. {
  11. public static void RegisterDependencies()
  12. {
  13. var builder = new ContainerBuilder();
  14. builder.RegisterControllers(typeof(MvcApplication).Assembly);
  15. builder.RegisterType<Log_UserLogonService>().As<ILog_UserLogon>().InstancePerLifetimeScope();
  16. builder.RegisterType<Log_UserOperateService>().As<ILog_UserOperate>().InstancePerLifetimeScope();
  17. //autofac 注册依赖
  18. IContainer container = builder.Build();
  19. DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
  20.     }
  21.  }
  22. }

在App_Start事件中调用上面的会依赖注入代码:

  1. using Lanhu.Core;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.linq;
  5. using System.Web;
  6. using System.Web.Mvc;
  7. using System.Web.Optimization;
  8. using System.Web.Routing;
  9. namespace Lanhu.Admin
  10. {
  11. public class MvcApplication : System.Web.HttpApplication
  12. {
  13. protected void Application_Start()
  14. {
  15. AreaRegistration.RegisterAllAreas();
  16. FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
  17. RouteConfig.RegisterRoutes(RouteTable.Routes);
  18. BundleConfig.RegisterBundles(BundleTable.Bundles);
  19. DependencyRegistrar.RegisterDependencies();
  20. }
  21. }
  22. }

LogFacade.cs:

  1. using Lanhu.Model;
  2. using Lanhu.Services;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using System.Web;
  9. using System.Web.Mvc;
  10. namespace Lanhu.Admin.Infrastructure
  11. {
  12. public class LogFacade
  13. {
  14. public static bool AddLogonLog(MLog_UserLogon model)
  15. {
  16. var service = DependencyResolver.Current.GetService<ILog_UserLogon>();
  17. return service.Insert(model);
  18. }
  19. public static bool AddOperateLog(string info,bool isError=false)
  20. {
  21. var service = DependencyResolver.Current.GetService<ILog_UserOperate>();
  22. if (isError)
  23. model.ErrorMsg = info;
  24. else
  25. model.Msg = info;
  26. return service.Insert(model);
  27. }
  28. public static bool AddOperateLog(MLog_UserOperate model)
  29. {
  30. var service = DependencyResolver.Current.GetService<ILog_UserOperate>();
  31. return service.Insert(model);
  32. }
  33. }
  34. }

上面封装了三个静态方法,在方法里面通过DependencyResolver.Current.GetService从Ioc容器中获取相应类型的依赖对象。这个LogFacade使用外观模式,让调用显得很简单。

依赖注入框架Autofac的简单使用

 话说nopcommerce底层用到了autofac框架,这里转了一篇文章简单说明一下:

Autofac是一款IOC框架,比较于其他的IOC框架,如Spring.NET,Unity,Castle等等所包含的,它很轻量级性能上也是很高的。于是,今天抽空研究了下它。下载地址:http://code.google.com/p/autofac/downloads/list

1)解压它的压缩包,主要看到Autofac.dll,Autofac.Configuration.dll,这也是本篇文章重点使用的Autofac的类库。

2)创建一个控制台工程,并且引用以上的DLL文件。创建一个数据库操作接口IDatabase.cs:

///<summary>
/// Database operate interface
///</summary>
public interface IDatabase
{
string Name { get; }

void Select(string commandText);

void Insert(string commandText);

void Update(string commandText);

void Delete(string commandText);
}

这里包含CRUD四种操作的方法。

 

3)创建两种数据库的操作类,SqlDatabase.cs以及OracleDatabase.cs:

 
public class SqlDatabase : IDatabase 
{ 
public string Name 
{ 
get { return "sqlserver"; } 
}

public void Select(string commandText) 
{ 
Console.WriteLine(string.Format("'{0}' is a query sql in {1}!", commandText, Name)); 
}

public void Insert(string commandText) 
{ 
Console.WriteLine(string.Format("'{0}' is a insert sql in {1}!", commandText, Name)); 
}

public void Update(string commandText) 
{ 
Console.WriteLine(string.Format("'{0}' is a update sql in {1}!", commandText, Name)); 
}

public void Delete(string commandText) 
{ 
Console.WriteLine(string.Format("'{0}' is a delete sql in {1}!", commandText, Name)); 
} 
} 

以及

 
public class OracleDatabase : IDatabase 
{ 
public string Name 
{ 
get { return "oracle"; } 
}

public void Select(string commandText) 
{ 
Console.WriteLine(string.Format("'{0}' is a query sql in {1}!", commandText, Name)); 
}

public void Insert(string commandText) 
{ 
Console.WriteLine(string.Format("'{0}' is a insert sql in {1}!", commandText, Name)); 
}

public void Update(string commandText) 
{ 
Console.WriteLine(string.Format("'{0}' is a update sql in {1}!", commandText, Name)); 
}

public void Delete(string commandText) 
{ 
Console.WriteLine(string.Format("'{0}' is a delete sql in {1}!", commandText, Name)); 
} 
}

4)接着创建一个数据库管理器DatabaseManager.cs:

public class DatabaseManager 
{ 
IDatabase _database;

public DatabaseManager(IDatabase database) 
{ 
_database = database; 
}

public void Search(string commandText) 
{ 
_database.Select(commandText); 
}

public void Add(string commandText) 
{ 
_database.Insert(commandText); 
}

public void Save(string commandText) 
{ 
_database.Update(commandText); 
}

public void Remove(string commandText) 
{ 
_database.Delete(commandText); 
}

}
 

5)在控制台中,编写以下测试程序:

var builder = new ContainerBuilder(); 
builder.RegisterType<DatabaseManager>(); 
builder.RegisterType<SqlDatabase>().As<IDatabase>(); 
using (var container = builder.Build()) 
{ 
var manager = container.Resolve<DatabaseManager>(); 
manager.Search("SELECT * FORM USER"); 
}

运行结果:

image

分析:

这里通过ContainerBuilder方法RegisterType对DatabaseManager进行注册,当注册的类型在相应得到的容器中可以Resolve你的DatabaseManager实例。

builder.RegisterType<SqlDatabase>().As<IDatabase>();通过AS可以让DatabaseManager类中通过构造函数依赖注入类型相应的接口。

Build()方法生成一个对应的Container实例,这样,就可以通过Resolve解析到注册的类型实例。

 

同样地,如果你修改数据库类型注册为:

builder.RegisterType<OracleDatabase>().As<IDatabase>();

运行结果:

image

 

6)显然以上的程序中,SqlDatabase或者OracleDatabase已经暴露于客户程序中了,现在我想将该类型选择通过文件配置进行读取。Autofac自带了一个Autofac.Configuration.dll 非常方便地对类型进行配置,避免了程序的重新编译。

修改App.config:

<configuration> 
<configSections> 
<section name="autofac" type="Autofac.Configuration.SectionHandler, Autofac.Configuration"/> 
</configSections> 
<autofac defaultAssembly="AutofacDemo"> 
<components> 
<component type="AutofacDemo.SqlDatabase, AutofacDemo" service="AutofacDemo.IDatabase"/> 
</components> 
</autofac> 
</configuration>
 

通过Autofac.Configuration.SectionHandler配置节点对组件进行处理。

对应的客户端程序改为:

var builder = new ContainerBuilder(); 
builder.RegisterType<DatabaseManager>(); 
builder.RegisterModule(new ConfigurationSettingsReader("autofac")); 
using (var container = builder.Build()) 
{ 
var manager = container.Resolve<DatabaseManager>(); 
manager.Search("SELECT * FORM USER"); 
} 

运行结果:

image


7)另外还有一种方式,通过Register方法进行注册:

var builder = new ContainerBuilder(); 
//builder.RegisterType<DatabaseManager>(); 
builder.RegisterModule(new ConfigurationSettingsReader("autofac")); 
builder.Register(c => new DatabaseManager(c.Resolve<IDatabase>())); 
using (var container = builder.Build()) 
{ 
var manager = container.Resolve<DatabaseManager>(); 
manager.Search("SELECT * FORM USER"); 
} 

得到结果也是一样的。

8)现在我想通过一个用户类来控制操作权限,比如增删改的权限,创建一个用户类:

///<summary> 
/// Id Identity Interface 
///</summary>
public interface Identity 
{ 
int Id { get; set; } 
} 


public class User : Identity 
{ 
public int Id { get; set; } 
public string Name { get; set; } 
}

修改DatabaseManager.cs代码:

 
public class DatabaseManager 
{ 
IDatabase _database; 
User _user;

public DatabaseManager(IDatabase database) : this(database, null) 
{ 
}

public DatabaseManager(IDatabase database, User user) 
{ 
_database = database; 
_user = user; 
}

///<summary> 
/// Check Authority 
///</summary> 
///<returns></returns>
public bool IsAuthority() 
{ 
bool result = _user != null && _user.Id == 1 && _user.Name == "leepy" ? true : false; 
if (!result) 
Console.WriteLine("Not authority!");

return result; 
}

public void Search(string commandText) 
{ 
_database.Select(commandText); 
}

public void Add(string commandText) 
{ 
if (IsAuthority()) 
_database.Insert(commandText); 
}

public void Save(string commandText) 
{ 
if (IsAuthority()) 
_database.Update(commandText); 
}

public void Remove(string commandText) 
{ 
if (IsAuthority()) 
_database.Delete(commandText); 
} 
} 

在构造函数中增加了一个参数User,而Add,Save,Remove增加了权限判断。

修改客户端程序:

User user = new User { Id = 1, Name = "leepy" }; 
var builder = new ContainerBuilder(); 
builder.RegisterModule(new ConfigurationSettingsReader("autofac")); 
builder.RegisterInstance(user).As<User>(); 
builder.Register(c => new DatabaseManager(c.Resolve<IDatabase>(), c.Resolve<User>()));

using (var container = builder.Build()) 
{ 
var manager = container.Resolve<DatabaseManager>();

manager.Add("INSERT INTO USER ..."); 
}
 

运行结果:

image
分析:

builder.RegisterInstance(user).As<User>();注册User实例。

builder.Register(c => new DatabaseManager(c.Resolve<IDatabase>(), c.Resolve<User>()));通过Lampda表达式注册DatabaseManager实例。

如果这里我修改User的属性值:

User user = new User { Id = 2, Name = "zhangsan" };

运行结果:

image

说明该用户无权限操作。