【发布时间】:2011-02-11 22:24:52
【问题描述】:
我的要求是创建一个可以使用标准 ASP.NET Profile 提供程序的框架。该应用程序包含两个库,一个用于 Profile 访问(使用 ProfileBase 类保存和检索 Profile)——一个框架类库,另一个用于定义 Profile 的属性——使用上述框架类库的开发者客户端类库。
这里的想法是开发人员不需要了解底层配置文件的实现(在框架类库中),他们所要做的就是在类中提供属性,以便可以设置和获取配置文件正如预期的那样。
我的实现如下。 (请注意,我已经成功配置了身份验证、连接字符串和角色提供者)
Web.config->
<profile inherits="MyCompany.FrameworkLib.ProfileSettingsService, MyCompany.FrameworkLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=12ac5ebb7ed144" >
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
</profile>
*Our design is not to specify profile properties in the web.config.
MyCompany.FrameworkLib.ProfileSettingsService 的实现->
public class ProfileSettingsService : ProfileBase, IProfileSettingsService
{
"**Note that if I un-comment the below code Profile works as expected. I do not want this property to be here, but somehow discover it dynamically based on the values being passed to this class. How can I do this?.**"
//[SettingsAllowAnonymous(false)]
//public string HideTransactionButton
//{
// get { return base["HideTransactionButton"] as string; }
// set { base["HideTransactionButton"] = value; }
//}
#region IProfileSettingsService Members
public T Get<T>(string key, T defaultValue)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException("key");
}
object profileValue = null;
try
{
profileValue = GetUserProfile().GetPropertyValue(key);
}
catch { }
if (profileValue is T)
{
return (T)profileValue;
}
return defaultValue;
}
public void Set<T>(string key, T value)
{
GetUserProfile().SetPropertyValue(key, value);
GetUserProfile().Save();
}
public ProfileSettingsService GetUserProfile(string username)
{
return Create(username) as ProfileSettingsService;
}
public ProfileSettingsService GetUserProfile()
{
var userName = HttpContext.User.Identity.Name;
if (userName != null)
{
return Create(userName) as ProfileSettingsService;
}
return null;
}
#endregion
}
MyCompany.ConsumeLib.ProfileContext 的实现 ->
public class ProfileContext : IProfileContext
{
#region IProfileContext Members
[Dependency] //Note that I use Unity for DI
public IProfileSettingsService ProfileSettingsService { get; set; }
public string HideTransactionButton
{
get { return this.ProfileSettingsService.Get<string>("HideTransactionButton", "false"); }
set { this.ProfileSettingsService.Set("HideTransactionButton", value); }
}
#endregion
}
所以问题是如何在不取消注释的情况下使配置文件正常工作
//[SettingsAllowAnonymous(false)]
//public string HideTransactionButton
//{
// get { return base["HideTransactionButton"] as string; }
// set { base["HideTransactionButton"] = value; }
//}
在 MyCompany.FrameworkLib.ProfileSettingsService 中
我需要能够在 ProfileSettingsService 中动态发现属性,而无需显式指定属性。这样,开发者就不用担心维护两个库中的属性了——(一个在frameworkLib中,另一个在ConsumeLib中。)
非常感谢任何想法。
【问题讨论】: