我正在为我的应用程序的某些部分应用提供程序模型。我不想将System.Web程序集添加到我的类库中。有没有办法在不使用ProvidersHelper.InstantiateProviders(System.Web.Configuration)的情况下实例化提供程序 非常感谢你!
答案 0 :(得分:2)
这个问题真的很老了,但我想我会分享我对这个问题的经验,对于这个问题的任何未来发现者。你可以很容易地实现自己的,有一些花哨的自动类型解析事件,system.web版本与内部HTTP助手一起使用,但如果你不需要其他方面,你可能不需要那些System.Web.dll
粗略的例子:
public static void InstantiateProviders(ProviderSettingsCollection configProviders,
ProviderCollection providers, Type providerType)
{
foreach (ProviderSettings providerSettings in configProviders)
providers.Add(InstantiateProvider(providerSettings, providerType));
}
InstantiateProviderMethod:
public static ProviderBase InstantiateProvider(ProviderSettings providerSettings, Type providerType)
{
ProviderBase providerBase;
try
{
string typeName = providerSettings.Type == null ? null : providerSettings.Type.Trim();
if (string.IsNullOrEmpty(typeName))
throw new ArgumentException("Provider has not type name.");
Type type = GetType(typeName, "type", providerSettings, null, true);
if (type.ContainsGenericParameters)
{ //if it is generic, we need to make sure the generic types get populated before checking inheritance and invokation
var genericTypes = providerType.GenericTypeArguments;
type = type.MakeGenericType(genericTypes);
}
if (!providerType.IsAssignableFrom(type))
{
throw new ArgumentException("provider must implement from type", providerType.ToString());
}
else
{
providerBase = (ProviderBase)Activator.CreateInstance(type);
NameValueCollection parameters = providerSettings.Parameters;
NameValueCollection config = new NameValueCollection(parameters.Count, StringComparer.Ordinal);
foreach (string index in parameters)
config[index] = parameters[index];
providerBase.Initialize(providerSettings.Name, config);
}
}
catch (exc)...
return providerBase;
}
那里的GetType
方法实际上只是解析类型并得到它(加上一些错误处理) - 但这真的是你所要做的。然后在Initialize(string name NameValueCollection config)
实施中的ProviderBase
方法中调用它。