标签: unity-container

使用第三方依赖注入容器而不是使用我构建的容器有什么好处?

我很久以前建造了一个IoC容器,几个月前看了这个节目http://www.dnrtv.com/default.aspx?showNum=126,并做了一个使用它的小样本,并且工作正常.

现在我在我正在开始的项目中使用unity作为依赖注入容器,并且还在之前的小型MVC网站中尝试了NInject.

但我现在问自己,这些容器比我从节目中创建的容器有什么好处,我只能看到它从配置文件中加载,我可以在我的网站上做,是否还有其他我缺少的东西?我只想要一个人告诉我你必须使用这些容器因为1,2,3个原因比你的好.

.net dependency-injection ninject ioc-container unity-container

3
推荐指数
1
解决办法
264
查看次数

Unity命名映射问题

我有两个实现IEmailService,一个用于测试,一个用于实时(is-A).我有一个BusinessService有-A IEmailService的参考.

BusinessService
    IEmailService (has-A)

IEmailService
    TestEmailService (is-A)
    LiveEmailService (is-A)
Run Code Online (Sandbox Code Playgroud)

在unity config中,我IEmailService按如下方式注册这两个实现.

<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<container>
  <register type="DataAccess.IEmailService, DataAccess"
            mapTo="DataAccess.LiveEmailService, DataAccess"
            name="Live">
    <lifetime type="singleton" />
  </register>
  <register type="DataAccess.IEmailService, DataAccess"
            mapTo="DataAccess.TestEmailService, DataAccess"
            name="Test">
    <lifetime type="singleton" />
  </register>
<container>
</unity>
Run Code Online (Sandbox Code Playgroud)

根据该appSettingIEmailService我要团结,挑选正确实施.这将有助于测试.

<appSettings>
    <add key="IEmailService" value="Test"/>
</appSettings>
Run Code Online (Sandbox Code Playgroud)

问题是当unity解析时BusinessService,它会尝试解析(none)命名映射IEmailService而不是Live或者Test抛出一个ResolutionFailedException.

container.Resolve<BusinessService>(); 抛出异常:

BusinessServices.Test.BusinessServiceTest_Integration.Test103:

Microsoft.Practices.Unity.ResolutionFailedException : Resolution of the dependency failed, type = "BusinessServices.BusinessService", …
Run Code Online (Sandbox Code Playgroud)

c# dependency-injection unity-container

3
推荐指数
1
解决办法
2万
查看次数

无法解析类型名称.请检查配置文件

尝试使用moq和unity对我的应用程序进行单元测试,我收到的错误是我的服务是一个接口,无法解决:

错误信息:

    Test method Ecommerce_Test.Tests.LoginSuccessfulRedirectToActionLoad threw exception: 
System.InvalidOperationException: The type name or alias Ecommerce_Test.AuthenticationMock could not be resolved. Please check your configuration file and verify this type name.
Run Code Online (Sandbox Code Playgroud)

错误堆栈跟踪:

    Microsoft.Practices.Unity.Configuration.ConfigurationHelpers.TypeResolverImpl.ResolveType(String typeNameOrAlias, Boolean throwIfResolveFails) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity.Configuration\Src\ConfigurationHelpers\TypeResolverImpl.cs: line 110
Microsoft.Practices.Unity.Configuration.RegisterElement.GetMappedType() in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity.Configuration\Src\RegisterElement.cs: line 128
Microsoft.Practices.Unity.Configuration.RegisterElement.ConfigureContainer(IUnityContainer container) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity.Configuration\Src\RegisterElement.cs: line 0
Microsoft.Practices.Unity.Configuration.ContainerElement.<>c__DisplayClass1.<ConfigureContainer>b__0(ContainerConfiguringElement element) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity.Configuration\Src\ContainerElement.cs: line 114
Microsoft.Practices.ObjectBuilder2.EnumerableExtensions.ForEach[TItem](IEnumerable`1 sequence, Action`1 action) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity\Src\ObjectBuilder\Utility\EnumerableExtensions.cs: line 36
Microsoft.Practices.Unity.Configuration.ContainerElement.ConfigureContainer(IUnityContainer container) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity.Configuration\Src\ContainerElement.cs: line 110
Microsoft.Practices.Unity.Configuration.UnityConfigurationSection.Configure(IUnityContainer container, String configuredContainerName) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity.Configuration\Src\UnityConfigurationSection.cs: line 151
Microsoft.Practices.Unity.Configuration.UnityContainerExtensions.LoadConfiguration(IUnityContainer container, UnityConfigurationSection section, …
Run Code Online (Sandbox Code Playgroud)

unit-testing moq unity-container unity2.0

3
推荐指数
1
解决办法
9969
查看次数

混合Unity Web API和MVC4 UnityDependencyResolvers:没有为此对象定义无参数构造函数

我收到以下异常:

No parameterless constructor defined for this object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.MissingMethodException: No parameterless constructor defined for this object.
Run Code Online (Sandbox Code Playgroud)

当框架尝试构造不是从ApiController派生的控制器时,例如下面的简单HomeController:

 public class HomeController : Controller
        {
            private IUnityContainer _unityContainer;
            public HomeController(IUnityContainer unityContainer)
            {
                _unityContainer = unityContainer;
            }
            public ActionResult Index()
            {
                return View();
            }
        }
Run Code Online (Sandbox Code Playgroud)

我定义了以下Boostrapper.cs类:

     public static class Boostrapper …
Run Code Online (Sandbox Code Playgroud)

c# unity-container asp.net-mvc-4

3
推荐指数
1
解决办法
5771
查看次数

安装Unity.Mvc4,但无法获得正确版本的Microsoft.Practices.Unity

我正在尝试安装Unity.Mvc4但是我收到此错误消息;

无法加载文件或程序集"Microsoft.Practices.Unity,Version = 2.1.505.0,Culture = neutral,PublicKeyToken = 31bf3856ad364e35"或其依赖项之一.定位的程序集的清单定义与程序集引用不匹配.(HRESULT异常:0x80131040)

我的Microsoft.Practices.Unity版本是3.0.0.0.为什么我要一个旧版本?

asp.net-mvc unity-container nuget

3
推荐指数
1
解决办法
4436
查看次数

Unity MVC GetService在后台线程抛出NullReferenceException

据我所知,DependencyResolver是线程安全的,但运行以下代码会在后台线程中引发空引用异常.

public interface ITest {

}
public class Test : ITest {

}

//this works fine
var service = DependencyResolver.Current.GetService<ITest>();

var t1 = Task.Run(() => {
   //This throws a Null Reference exception.
   // note that DependencyResolver.Current is NOT null.  
   // The exception occurs in GetService
   var s1 = DependencyResolver.Current.GetService<ITest>();
});
Task.WaitAll(t1);
Run Code Online (Sandbox Code Playgroud)

这是堆栈跟踪:

at Unity.Mvc4.UnityDependencyResolver.get_ChildContainer()
at Unity.Mvc4.UnityDependencyResolver.IsRegistered(Type typeToCheck)
at Unity.Mvc4.UnityDependencyResolver.GetService(Type serviceType)
at System.Web.Mvc.DependencyResolverExtensions.GetService[TService](IDependencyResolver resolver)
at System.Threading.Tasks.Task.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
Run Code Online (Sandbox Code Playgroud)

我知道"服务定位器"模式是一种反模式.在这一点上,我只是想了解为什么这不起作用.

任何见解将不胜感激.

谢谢!

multithreading unity-container service-locator asp.net-mvc-3

3
推荐指数
1
解决办法
1472
查看次数

使用unity xml config注册具有嵌套泛型的接口

如果我有一个实现通用接口的类,可以使用unity xml config配置它.

public interface IReader<T> { }

public class Fund { }

public class FundReader : IReader<Fund> { }
Run Code Online (Sandbox Code Playgroud)

和统一xml:

<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
  <namespace name="System.ComponentModel" />
  <namespace name="TestUnityIssue" />
  <assembly name="TestUnityIssue" />
  <container>
    <register type="IReader[Fund]" mapTo="FundReader" />
  </container>
</unity>
Run Code Online (Sandbox Code Playgroud)

这只是使用以下代码:

var container = new UnityContainer().LoadConfiguration();
var fundReader = container.Resolve<IReader<Fund>>();
Run Code Online (Sandbox Code Playgroud)

但是,在某些情况下,阅读器中使用的类型周围有一个包装器.例如,添加以下两个类:

public class Wrapper<T> { }

public class WrappedFundReader : IReader<Wrapper<Fund>> { }
Run Code Online (Sandbox Code Playgroud)

如果我将以下内容添加到unity配置中:

<register type="IReader[Wrapper[Fund]]" mapTo="WrappedFundReader" />
Run Code Online (Sandbox Code Playgroud)

然后尝试使用以下方法解决它:

var wrappedReader = container.Resolve<IReader<Wrapper<Fund>>>();
Run Code Online (Sandbox Code Playgroud)

我得到以下异常:

InvalidOperationException - The current type,
TestUnityIssue.IReader`1[TestUnityIssue.Wrapper`1[TestUnityIssue.Fund]],
is …
Run Code Online (Sandbox Code Playgroud)

c# xml generics unity-container

3
推荐指数
1
解决办法
2876
查看次数

Moq与Unity Container单元测试

下面是我试图进行单元测试的生产代码示例.我正在努力解决对正在使用的具体类的依赖.

public MyClass(IUnityContainer container)
{
    this.unityContainer = container;
}

public string DoWork()
{
     var sender = unityContainer.Resolve<IInterface>();  // how to setup this object
     var json = sender.Send("something");
     var value = serializer.Deserialize<SomeModel>(json);
     return value.url;
}
Run Code Online (Sandbox Code Playgroud)

我想模仿这种方法使用的IInterface.如何在我的单元测试代码中进行设置?我觉得这里缺少一些东西.这有一种反模式的气味......

c# unit-testing moq unity-container

3
推荐指数
1
解决办法
1万
查看次数

使用Unity在WebAPI中注入依赖项

我有一个(应该)看起来像这样的WebAPI控制器:

public class MyController : ApiController
{
    private IRepository repository;

    public MyController(IRepository repository) 
    {
        this.repository = repositor;
    }

    // REST implementations
}
Run Code Online (Sandbox Code Playgroud)

WebApiConfig 配置如下:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Unity configuration
        var container = new UnityContainer();
        container
            .RegisterType<IRepository , CustomRepository>();
        config.DependencyResolver = new UnityResolver(container);

        // Web API routes
        // CORS
    }
}
Run Code Online (Sandbox Code Playgroud)

然后Global.asax.cs我有类似的东西:

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }

    // CORS
    protected void Application_BeginRequest(object sender, …
Run Code Online (Sandbox Code Playgroud)

c# unity-container asp.net-web-api

3
推荐指数
2
解决办法
2万
查看次数

IUserStore [Models.ApplicationUser]不会由Unity接口解析为Class,而是由InjectionConstructor解析

当我尝试调用Accounts控制器时,我得到了该错误,

[InvalidOperationException:当前类型Microsoft.AspNet.Identity.IUserStore`1 [Proj1.Web.Models.ApplicationUser]是一个接口,无法构造。您是否缺少类型映射?]

但是经过搜索我得到了它的支持;

container.RegisterType<AccountController>(new InjectionConstructor());
Run Code Online (Sandbox Code Playgroud)

但是,为什么这个错误排在首位呢?

帐户控制器的参数少了构造函数,

  public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager )
        {
            UserManager = userManager;
            SignInManager = signInManager;
        }
Run Code Online (Sandbox Code Playgroud)

然后ApplicationUserManager具有以下参数较少的构造函数。

public ApplicationUserManager(IUserStore<ApplicationUser> store)
            : base(store)
        {
        }
Run Code Online (Sandbox Code Playgroud)

因此,依赖项为IUserStore。

现在,作为我的标准做法,我将执行以下操作:

  container.RegisterType<IUserStore<ApplicationUser>,UserStore<ApplicationUser>>();
Run Code Online (Sandbox Code Playgroud)

但是相反,我们在做,感觉就像魔术

container.RegisterType<AccountController>(new InjectionConstructor());
Run Code Online (Sandbox Code Playgroud)

上面的线是什么意思?

c# asp.net-mvc dependency-injection inversion-of-control unity-container

3
推荐指数
1
解决办法
1571
查看次数