Это работает для меня на веб-сервере предприятия, над которым я работаю уже несколько месяцев. Он имеет n-уровневую архитектуру с уровнем данных, который имеет .cs-файлы, которые заканчиваются на «репозиторий». Хотя я согласен с другим сообщением, Интерфейсы должны быть разделены, в моем веб-api они не реализованы таким образом.
using System;
using System.Web.Http;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using Unity.WebApi;
namespace Blah.Endpoints.App_Start
{
/// <summary>
/// Specifies the Unity configuration for the main container.
/// </summary>
public static class UnityConfig
{
public static void RegisterComponents()
{
var container = new UnityContainer();
// register all your components with the container here
// it is NOT necessary to register your controllers
RegisterTypes(container);
// e.g. container.RegisterType<ITestService, TestService>();
GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
}
#region Unity Container
private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
{
var container = new UnityContainer();
RegisterTypes(container);
return container;
});
/// <summary>
/// Gets the configured Unity container.
/// </summary>
public static IUnityContainer GetConfiguredContainer()
{
return container.Value;
}
#endregion
/// <summary>Registers the type mappings with the Unity container.</summary>
/// <param name="container">The unity container to configure.</param>
/// <remarks>There is no need to register concrete types such as controllers or API controllers (unless you want to
/// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.</remarks>
public static void RegisterTypes(IUnityContainer container)
{
container.RegisterTypes(AllClasses.FromLoadedAssemblies(),
WithMappings.FromMatchingInterface,
WithName.Default,
null, //WithLifetime IF we want to change the lifetime aspect aka Singletons
null,//GetMembers,
false
);
}
}
}
Эта настройка обычно работает для моей команды. Иногда мы все еще получаем классы, которые бросают ошибки единства без всякой видимой причины. Для тех мы делаем что-то подобное;
public class WcfServiceFactory : UnityServiceHostFactory
{
protected override void ConfigureContainer(IUnityContainer container)
{
//Attach hook for AOP attributes
container.AddNewExtension<Interception>();
// register all your components with the container here
// container
// .RegisterType<IService1, Service1>()
// .RegisterType<DataContext>(new HierarchicalLifetimeManager());
container.RegisterTypes(AllClasses.FromLoadedAssemblies(),
WithMappings.FromMatchingInterface,
WithName.Default,
null, //WithLifetime IF we want to change the lifetime aspect aka Singletons
GetMembers,
false
);
container.RegisterType<IPaymentService, PaymentService>();
container.RegisterType<IPaymentManager, PaymentManager>();
container.RegisterType<IPaymentMethodRepository, PaymentMethodRepository>();
container.RegisterType<IPaymentWithdrawScheduleRepository, PaymentWithdrawScheduleRepository>();
container.RegisterType<IPaymentPreEnrollmentRepository, PaymentPreEnrollmentRepository>();
container.RegisterType<ISharedLoanDataRepository<tblPaymentMethod>, SharedLoanDataRepository<tblPaymentMethod>>();
container.RegisterType<ISharedLoanDataRepository<tblPaymentWithdrawSchedule>, SharedLoanDataRepository<tblPaymentWithdrawSchedule>>();
container.RegisterType<IPaymentWithdrawScheduleOffSetTypeRepository, PaymentWithdrawScheduleOffSetTypeRepository>();
container.RegisterType<IPaymentMethodTypeRepository, PaymentMethodTypeRepository>();
container.RegisterType<IPaymentWithdrawScheduleFrequencyTypeRepository, PaymentWithdrawScheduleFrequencyTypeRepository>();
container.RegisterType<IPaymentCustomerNotificationRepository, PaymentCustomerNotificationRepository>();
container.RegisterType<ITraceLogger, TraceLogger>();
container.RegisterType<IPaymentWithdrawScheduleCancelReasonRepository, PaymentWithdrawScheduleCancelReasonRepository>();
}
private IEnumerable<InjectionMember> GetMembers(Type type)
{
var list = new List<InjectionMember>();
list.Add(new InterceptionBehavior<PolicyInjectionBehavior>(type.ToString()));
list.Add(new Interceptor<InterfaceInterceptor>(type.ToString()));
return list;
}
}
Я надеюсь, что это помогает
С уважением.
Можете ли вы предоставить ссылку на сообщение в блоге, на которое вы ссылаетесь? – Necoras
Я добавил ulr в сообщение в блоге –
Вы имеете в виду классы, чье имя заканчивается на «Репозиторий», правильно? У вас есть ссылки на проект «CManager.Repository» из корневого проекта композиции (проект, в котором вы используете Unity)? –