我几乎拥有标准的Unity设置
ICardRepository:
public interface ICardRepository {
Task<Card> Get(GetCardRequest request);
}
[DataContract]
public class GetCardRequest {
[DataMember(IsRequired = true)]
public int CardID { get; set; }
}
DbCardRepository:
public class DbCardRepository : CardCornerDbRepository, ICardRepository {
public DbCardRepository(IDbConfig config) : base(config) {
}
public async Task<Card> Get(GetCardRequest request) {
try {
return await ExecuteGetRequestAsync<Card>(request, "p_CardsTest");
} catch (Exception ex) {
throw;
}
}
Web.Config中:
<configuration>
<configSections>
...
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
</configSections>
<connectionStrings>
<add name="System" providerName="System.Data.SqlClient"
connectionString="Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=CardCorner;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" />
</connectionStrings>
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<container>
<register type="CardCorner.Data.ICardRepository, CardCorner.Data" mapTo="CardCorner.Data.SqlClient.DbCardRepository, CardCorner.Data.SqlClient" />
</container>
</unity>
...
UnityConfig.cs
namespace CardCorner.App_Start
{
public class UnityConfig
{
#region Unity Container
private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
{
var container = new UnityContainer();
RegisterTypes(container);
return container;
});
public static IUnityContainer GetConfiguredContainer()
{
return container.Value;
}
#endregion
public static void RegisterTypes(IUnityContainer container)
{
container.LoadConfiguration();
var config = ConfigurationManager.ConnectionStrings["System"];
container.RegisterInstance<IDbConfig>(new DbConfigProvider(config.ConnectionString, config.ProviderName));
container.RegisterInstance<IDependancyResolver>(new CardCornerUIDependancyResolver());
}
}
public class CardCornerUIDependancyResolver : IDependancyResolver {
public object Resolve(Type type) {
return UnityConfig.GetConfiguredContainer().Resolve(type);
}
public T Resolve<T>() {
return UnityConfig.GetConfiguredContainer().Resolve<T>();
}
}
public class DbConfigProvider : IDbConfig {
private readonly String _connectionString;
private readonly String _providerName;
public DbConfigProvider(String connectionString, String providerName) {
this._connectionString = connectionString;
this._providerName = providerName;
}
public string ConnectionString {
get {
return _connectionString;
}
}
public string ProviderName {
get {
return _providerName;
}
}
}
}
UnityMvcActivator是如何出现的。这应该是所需要的一切,但如果没有,请问。然后我尝试使用它......
HomeController中:
private ICardRepository cardRepository;
public HomeController(ICardRepository cardRepository) {
this.cardRepository = cardRepository;
...
它抛出了这个错误:
我使用过卡片作为例子,但它们大致相同。看起来第二个错误只是因为第一个错误。我是Unity的新手,并不知道映射失败的原因。任何帮助将不胜感激。