给定这个接口:
public interface ILoanCalculator
{
decimal Amount { get; set; }
decimal TermYears { get; set; }
int TermMonths { get; set; }
decimal IntrestRatePerYear { get; set; }
DateTime StartDate { get; set; }
decimal MonthlyPayments { get; set; }
void Calculate();
}
和它的2个实现:
namespace MyCompany.Services.Business.Foo
{
public interface ILoanCalculator : Common.ILoanCalculator
{
}
public class LoanCalculator : ILoanCalculator
{
public decimal Amount { get; set; }
public decimal TermYears { get; set; }
public int TermMonths { get; set; }
public decimal IntrestRatePerYear { get; set; }
public DateTime StartDate { get; set; }
public decimal MonthlyPayments { get; set; }
public void Calculate()
{
throw new NotImplementedException();
}
}
}
namespace MyCompany.Services.Business.Bar
{
public interface ILoanCalculator : Common.ILoanCalculator
{
}
public class LoanCalculator : ILoanCalculator
{
public decimal Amount { get; set; }
public decimal TermYears { get; set; }
public int TermMonths { get; set; }
public decimal IntrestRatePerYear { get; set; }
public DateTime StartDate { get; set; }
public decimal MonthlyPayments { get; set; }
public void Calculate()
{
throw new NotImplementedException();
}
}
}
鉴于上面的简单代码,假设每个公司的计算方法的实现会有所不同。在初始化期间加载程序集并调用正确程序集的正确方法的正确方法是什么?我已经弄清楚了最简单的部分是确定请求是针对哪家公司的,现在我只需要调用与当前业务相对应的正确方法。
谢谢你,斯蒂芬
更新的示例代码
向@Scott 大声喊叫,这是我必须做出的改变,才能使接受的答案正常工作。
在这种情况下,我必须使用 Assembly Resolver 来查找我的类型。请注意,我使用属性来标记我的程序集,以便基于它的过滤更简单且不易出错。
public T GetInstance<T>(string typeName, object value) where T : class
{
// Get the customer name from the request items
var customer = Request.GetItem("customer") as string;
if (customer == null) throw new Exception("Customer has not been set");
// Create the typeof the object from the customer name and the type format
var assemblyQualifiedName = string.Format(typeName, customer);
var type = Type.GetType(
assemblyQualifiedName,
(name) =>
{
return AppDomain.CurrentDomain.GetAssemblies()
.Where(a => a.GetCustomAttributes(typeof(TypeMarkerAttribute), false).Any()).FirstOrDefault();
},
null,
true);
if (type == null) throw new Exception("Customer type not loaded");
// Create an instance of the type
var instance = Activator.CreateInstance(type) as T;
// Check the instance is valid
if (instance == default(T)) throw new Exception("Unable to create instance");
// Populate it with the values from the request
instance.PopulateWith(value);
// Return the instance
return instance;
}
标记属性
[AttributeUsage(AttributeTargets.Assembly)]
public class TypeMarkerAttribute : Attribute { }
在插件程序集中的使用
[assembly: TypeMarker]
最后,对静态 MyTypes 稍作更改以支持限定名称
public static class MyTypes
{
// assemblyQualifiedName
public static string LoanCalculator = "SomeName.BusinessLogic.{0}.LoanCalculator, SomeName.BusinessLogic.{0}, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
}