在这篇Autofac IoC 文章中,他们展示了一个使用参数将接口映射到实现的示例.你会发现它在文章的中间.
什么是XML中的Unity等价物?不能使用流畅的语法来做我正在做的事情.需要是一个外部配置文件.
更新:
这是我想知道在Unity中如何做的特定代码 -
<component id="DataStoreProvider"
service="Company.Server.IDataStoreProvider,Company.Server.Interface"
type="Company.Server.DataStoreProvider,Company.Server.Core">
<parameters>
<connectionString>My Connection String</connectionString>
</parameters>
</component>
Run Code Online (Sandbox Code Playgroud)
也许不是以这种方式传递连接字符串的最好的例子......但是你明白了.我想知道如何在Unity中用XML做参数.
.net configuration ioc-container inversion-of-control unity-container
在Unity 2.0中创建子容器的成本(性能影响)有多大?该场景是例如Web应用程序或Web服务,其中主容器在应用程序启动时被初始化,但是每个处理的请求具有其自己的从主要创建的子容器的实例.容器的配置不会改变.原因是使用HierarchicalLifetimeManager.
我正在开发一个Silverlight应用程序,我已经介绍Unity了它.
我遇到的问题是我不知道如何获取容器的实例.
我在ApplicationStartup方法上创建了这个intanceApp
_container = new UnityContainer();
_container.RegisterType<IMyAppServiceAgent, MyAppServiceAgent>(new InjectionConstructor(OriginalHandlerId, W2OGuid, ServiceEndpointAddr));
Run Code Online (Sandbox Code Playgroud)
我写了一个吸气剂
public IUnityContainer Container
{
get { return _container; }
}
Run Code Online (Sandbox Code Playgroud)
一切正常,这就是我如何使用我的容器:
public static void CreateMemberSearch()
{
if (_memberSearch == null)
{
_memberSearch =
new MemberSearchViewModel((App.Current as App).Container.Resolve<IMyAppServiceAgent>());
}
}
Run Code Online (Sandbox Code Playgroud)
以上示例来自ViewModelLocator(from MVVM Light Toolkit).
我需要知道如何重构我的代码以符合IOC原则.
我正在使用Microsoft Prism和Unity 编写模块化应用程序.我的应用程序的Shell项目加载各种DLL,这些DLL都包含自己的/ resources或/ images文件夹和用户界面视图.因此,每个模块都是DLL.
当我尝试在我的应用程序中使用资源时,似乎我必须非常清楚它的位置以使其工作.例如,要在同一模块/ dll中定位图像:
<Image Source="pack://application:,,,/MyCompany.MyProduct.MyModule;Component/Images/ZoomIn.gif" />
Run Code Online (Sandbox Code Playgroud)
我是否真的每次都必须使用URI的长格式版本?我尝试过更短的版本,例如:
pack://application:,,,/Images/ZoomIn.gif
Images/ZoomIn.gif
ZoomIn.gif
Run Code Online (Sandbox Code Playgroud)
等等
我想也许第二个版本应该有效.当我看到Uri的例子时,他们经常说"相对于当前的集会".这是正在运行的可执行程序的程序集吗?或者这是代码所属的程序集(我的库/模块)?
更新:
在Peter Hansen的帮助下,我能够将其缩短为:
<Image Source="../Images/ZoomOut.png" />
Run Code Online (Sandbox Code Playgroud)
显然我不得不使用../因为我的视图是在子文件夹中.我也可以放弃pack://语法,因为类型转换器为我做了这个.
在我正在使用此代码的类中:
public User CurrentUser
{
get
{
var unityContainer = new UnityContainer();
var httpContextHelper = unityContainer.Resolve<HttpContextHelper>();
return httpContextHelper.GetUser();
}
}
Run Code Online (Sandbox Code Playgroud)
这是在Bootstrapper.cs文件中:
public static class Bootstrapper
{
public static void Initialise()
{
IUnityContainer unityContainer = new UnityContainer();
unityContainer.RegisterType<IHttpContextHelper, HttpContextHelper>();
DependencyResolver.SetResolver(new UnityDependencyResolver(unityContainer));
}
}
Run Code Online (Sandbox Code Playgroud)
我不能在这里使用构造函数注入,因为它是一个基类,重构需要相当多的工作.
但是我如何对此进行单元测试呢?我找不到合适的模拟方法unityContainer.Resolve.
我最近开始使用统一,它似乎工作得很好,除了一个地方......我做了一些搜索,但我没有找到任何我可以应用于我的代码.
继承注册类型的代码:
Container.RegisterType<IVsoCommunicator, VsoCommunicator>();
Container.RegisterType<IIpxConnection, IpxCommunicator>();
Container.RegisterType<IConsentService, ConsentService>(new InjectionFactory(p => new ConsentService(p.Resolve<IIpxConnection>(), p.Resolve<IVsoCommunicator>())));
Container.RegisterType<ITimer, ConsentStatusPoller>(new InjectionFactory(p => new ConsentStatusPoller(p.Resolve<IConsentService>())));
Run Code Online (Sandbox Code Playgroud)
例外情况:
Resolution of the dependency failed, type = "UserManager.Services.ConsentStatusPoller", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The type IConsentService does not have an accessible constructor.
-----------------------------------------------
At the time of the exception, the container was:
Resolving UserManager.Services.ConsentStatusPoller,(none)
Resolving parameter "consentService" of constructor UserManager.Services.ConsentStatusPoller(UserManager.Services.IConsentService consentService)
Resolving UserManager.Services.IConsentService,(none)
Run Code Online (Sandbox Code Playgroud)
我在这做错了什么?首先,我认为我有私事,但事实并非如此
将注册更改为:
Container.RegisterType<ISettingsConfiguration, SettingsConfiguration>();
Container.RegisterType<IUnitOfWork, UnitOfWork>();
Container.RegisterType<IVsoCommunicator, VsoCommunicator>();
Container.RegisterType<IIpxConnection, IpxCommunicator>(); …Run Code Online (Sandbox Code Playgroud) 我不明白我们如何注册一个IEventAggregator实例,所以我们可以将它注入一个实例ViewModel.
例:
我定义了我的MainViewModel:
...
private IEventAggregator _eventAggregator;
public MainViewModel(IEventAggregator eventAggregator) {
_eventAggregator = eventAggregator;
...
}
...
Run Code Online (Sandbox Code Playgroud)
然后,我需要以某种方式注册一个实现IEventAggregator我想要注入的类ViewModel.
在我的ModuleInit班上,我会有这样的事情:
...
private IUnityContainer _container;
public ModuleInit(IUnityContainer _container) {
_container = container;
}
...
public void Initialize() {
container.RegisterType<IEventAggregator, ___(something)___>();
...
}
Run Code Online (Sandbox Code Playgroud)
在我的MainViewModel班上,我也可以实现_eventAggregator = ServiceLocator,Current.GetInstance<IEventAggregator>();,但我从概念上并不真正理解我在做什么.该计划正常运作......
我真的很想了解ServiceLocator实际上在做什么,以及我应该做些什么来适当地使用我的容器注册一个类型.我没有定义类的实现IEventAggregator,那么ServiceLocator获取实例的位置是什么?然后我必须注册什么才能当我解决某些问题时,就像我一样ViewModel,它会创建一个新EventAggregator实例?
我们有一个使用Unity 2.1.505.0的应用程序.我们的应用程序使用Web.API和自定义DependencyResolverAdapter来为我们的API控制器启用依赖注入.在这个适配器里面,我们调用了CreateChildContainer()方法IUnityContainer.但是,这个电话间歇地抛出一个NullReferenceException:
在什么情况下此方法会抛出NullReferenceException? 堆栈跟踪没有显示任何明显的原因:
at Microsoft.Practices.Unity.UnityContainer..ctor(UnityContainer parent)
at Microsoft.Practices.Unity.UnityContainer.CreateChildContainer()
at MyApp.DependencyResolverAdapter.BeginScope() in C:\ResCollection\CropProtection\MyApp\MyApp\DependencyResolverAdapter.cs:line 43
at System.Net.Http.HttpRequestMessageExtensions.GetDependencyScope(HttpRequestMessage request)
at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)
at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
Run Code Online (Sandbox Code Playgroud)
奇怪的是,在做了"清洁解决方案"后,应用程序正常工作约20-30秒; 控制器由Unity正确解决,解析器似乎正在完成其工作.然后NullReferenceException抛出,并且在应用程序的生命周期的剩余时间内没有成功解析控制器.重新运行应用程序(不先清除)会在第一次解析控制器时立即导致此错误.
c# dependency-injection unity-container asp.net-web-api asp.net-web-api2
从ReflectionHelper在Microsoft.Practices.Unity.InterceptionExtension...
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods",
Justification = "Validation done by Guard class")]
public static TAttribute[] GetAttributes<TAttribute>(MemberInfo member, bool inherits) where TAttribute : Attribute
{
Microsoft.Practices.Unity.Utility.Guard.ArgumentNotNull(member, "member");
IEnumerable<Object> attributesAsObjects = member.GetCustomAttributes(typeof(TAttribute), inherits);
TAttribute[] attributes = new TAttribute[attributesAsObjects.Count()];
int index = 0;
attributesAsObjects.ForEach(attr =>
{
var a = (TAttribute) attr;
attributes[index++] = a;
});
return attributes;
}
public static IEnumerable<T> ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)
{
foreach (T item in enumeration)
{
action(item);
yield return item;
}
}
Run Code Online (Sandbox Code Playgroud)
attributesAsObjects包含一个元素. …
我ExceptionLogger用来处理所有全局异常。我的继承类要求注入依赖项以进行Nlog调用。
public class NLogExceptionLogger : ExceptionLogger
{
private readonly ILoggingService _loggingService;
public NLogExceptionLogger(ILoggingService<NLogExceptionLogger> loggingService)
{
_loggingService = loggingService;
}
public override void Log(ExceptionLoggerContext context)
{
_loggingService.FirstLevelServiceLog(context.Exception.StackTrace);
}
}
Run Code Online (Sandbox Code Playgroud)
LoggingService类别:
public class LoggingService<T> : ILoggingService<T>
{
private readonly ILogger _logger;
public LoggingService()
{
string currentClassName = typeof(T).Name;
_logger = LogManager.GetLogger(currentClassName);
}
public void FirstLevelServiceLog(string log)
{
_logger.Log(LogLevel.Debug, log);
}
}
Run Code Online (Sandbox Code Playgroud)
我的Unity代码:
public static UnityContainer RegisterComponents()
{
var container = new UnityContainer();
container.RegisterType(typeof(ILoggingService<>), typeof(LoggingService<>))
}
Run Code Online (Sandbox Code Playgroud)
我正在ExceptionLogger通过以下方式进行全局注册:(在这一行上,我收到一个错误) …
unity-container ×10
c# ×6
mvvm ×3
.net ×2
wpf ×2
asp.net-mvc ×1
moq ×1
performance ×1
prism ×1
silverlight ×1
unit-testing ×1