我有一个类型的类ISimpleCache<IBrokeredDataObject>,我想在App.Config文件中添加为类型别名(然后是类型)
这条线
<typeAlias alias="ISimpleCacheOfIBrokeredDataObject" type="MyApplication.ISimpleCache<IBrokeredDataObject>, MyApplication" />
Run Code Online (Sandbox Code Playgroud)
由于<>显然是错误的,但我不相信逃避它们;
<typeAlias alias="ISimpleCacheOfIBrokeredDataObject" type="MyApplication.ISimpleCache<IBrokeredDataObject>, MyApplication" />
Run Code Online (Sandbox Code Playgroud)
也是正确的.
我目前正在将我的代码拆分为使用Unity,因此距离可编译的代码库太远而无法快速测试,并希望在此处得到一些确认.
我正在使用Unity IoC容器,我需要拦截对Resolve的任何调用以获取某个基本接口,并运行我自己的自定义代码来构造这些类型.
换句话说,在下面的示例代码中,当我调用时container.Resolve<IFooN>(),如果它没有具体实现类型的实例,则调用MyFactoryFunction构造一个,否则我希望它返回缓存副本.
标准Unity容器无法构造这些对象(更新:因为它们是.NET远程处理对象,因此本地计算机上的任何程序集中都不存在具体类),我不想在前面创建它们用RegisterInstance存储它们.
interface IFoo : IBase { ... }
interface IFoo2 : IBase { ... }
...
container.Resolve<IFoo2>();
...
IBase MyFactoryFunction(Type t)
{
...
}
Run Code Online (Sandbox Code Playgroud)
我假设我可以创建一个Unity扩展来执行此操作,但我想知道是否已经有一个解决方案我可以借用.
我试图在Unity 2.0的配置文件中注册一个泛型类型,但似乎无法正确.我在这里指的是MS文档:http://msdn.microsoft.com/en-us/library/ff660933%28v=PandP.20%29.aspx#_Generic_Types
代码如下所示:
public interface IRepository<T> where T : class
{
...
}
public class GenericRepository<T> : IRepository<T> where T : class
{
...
}
public class BlogRepository : GenericRepository<BlogRepository>
{
...
}
Run Code Online (Sandbox Code Playgroud)
我目前的XML配置是这样的:
<unity>
<!-- Aliases -->
<alias alias="BlogIRepository"
type="X.Services.Interfaces.IRepository[[X.Domain.Entities.Blog, X.Domain]], X.Services"/>
<alias alias="BlogRepository"
type="X.Repositories.BlogRepository, X.Repositories"/>
<!-- Type registration -->
<container name="development">
<!-- Common connection string value -->
<instance name="Conn" type="System.String" value="blahblahblah"/>
<register type="BlogIRepository" mapTo="BlogRepository">
<constructor>
<param name="connectionString" type="System.String" dependencyName="Conn"/>
</constructor>
</register>
</container>
</unity>
Run Code Online (Sandbox Code Playgroud)
根据注册泛型类型的文档,你周围使用泛型类型方括号,如果类型不是系统类型你提供完全限定的类型里面更多的方括号.我想,这就是我所做的.然而 - …
.net generics configuration inversion-of-control unity-container
我有一个内部构造函数的类,想要从Unity(2.0)解析它.
public class MyClass {
internal MyClass(IService service) {
}
}
Run Code Online (Sandbox Code Playgroud)
然后我在做
_container.Resolve<MyClass>();
Run Code Online (Sandbox Code Playgroud)
当我这样做时,我有一个例外
Exception is: InvalidOperationException - The type MyClass cannot be constructed.
Run Code Online (Sandbox Code Playgroud)
IService已注册,唯一的问题是构造函数是内部的.我真的希望这个类是公开的,但是我希望它只能通过工厂(我实际上在调用它container.Resolve<MyClass>())中创建.
有没有办法让Unity看到内部构造函数?像InternalsVisibleTo或者什么?
我的目标是构造函数注入实现接口的对象数组.
以下是我目前的方式.
Container
.RegisterInstance<Company>(ParseCompany(args[1])
.RegisterInstance<eTargets>(ParseTargets(args[2]))
.RegisterInstance<ILoader[]>(new ILoader[] {
Container.Resolve<CustomerLoader>(),
Container.Resolve<PaymentLoader(),
Container.Resolve<InvoiceLoader()
});
Run Code Online (Sandbox Code Playgroud)
以这种方式调用容器配置中的Resolve是典型的,还是有更标准的方法来完成同样的事情?
想象一下,我们有一堂课
public class MyClass
{
private string _val;
public MyClass(string val)
{
_val = val;
}
}
Run Code Online (Sandbox Code Playgroud)
和app.config(或web.config)
<appSettings>
<add key="value" value="some value" />
</appSettings>
Run Code Online (Sandbox Code Playgroud)
有没有办法在Unity容器中注册MyClass类型并指向Unity从配置文件中为val构造函数参数注入值?
是否可以将Unity配置为检测循环引用或拦截类型解析器以显示某些调试信息?
这里有几个相互依赖的接口和类
public interface IThing1 { }
public class Thing1 : IThing1
{
private IThing2 _thing2;
public Thing1(IThing2 thing2)
{
_thing2 = thing2;
}
}
public interface IThing2 { }
public class Thing2 : IThing2
{
private IThing1 _thing1;
public Thing2(IThing1 thing1)
{
_thing1 = thing1;
}
}
Run Code Online (Sandbox Code Playgroud)
如果在Castle Windsor中配置了这两种类型,它将抛出异常并提供一些调试信息以查找循环引用:
Castle.MicroKernel.CircularDependencyException: Dependency cycle has been detected when trying to resolve component 'CircularIoC.Thing1'.
The resolution tree that resulted in the cycle is the following:
Component 'CircularIoC.Thing1' resolved as dependency …Run Code Online (Sandbox Code Playgroud) castle-windsor circular-dependency inversion-of-control unity-container
我的ASP.Net MVC 4 Web API控制器不适用于Unity.WebApi.在同一个项目中,简单的控制器可以正常使用Unity.Mvc3.但是,当我运行从ApiController派生的Web API控制器时,我收到一条消息:
{"$ id":"1","Message":"发生错误.","ExceptionMessage":"类型'ElectricTests.Controllers.Api.DocumentsController'没有默认构造函数","ExceptionType":" System.Web.Http.Internal.TypeActivator.Create [TBase](Type instanceType)\ r \"System.Linq.Expressions.Expression.New(Type type)\ r \n的System.ArgumentException","StackTrace":" n在System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage请求,类型controllerType,Func`1和激活器)\ r \n在System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage请求,HttpControllerDescriptor controllerDescriptor,类型controllerType) )"}
我的ApiController:
public class DocumentsController : ApiController
{
private readonly IDocumentsRepository _repository;
public DocumentsController(IDocumentsRepository repository) {
_repository = repository;
}
public IEnumerable<FormattedDocument> GetFormattedDocuments()
{
return _repository.GetAllFormattedDocuments();
}
...
Run Code Online (Sandbox Code Playgroud)
Bootstrapper.cs:
public static class Bootstrapper {
public static void Initialise() {
IUnityContainer container = BuildUnityContainer();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
private static IUnityContainer BuildUnityContainer() {
var container = new UnityContainer();
// register all your …Run Code Online (Sandbox Code Playgroud) 尝试使用Unity.Mvc5和使用Identity 2.0和Identity 2.0 Samples样板的MVC 5应用程序配置Unity时,我得到以下异常.我已经阅读了这个SO 配置Unity DI的ASP.NET身份,我仍然不清楚我错过了什么.我在这做错了什么?
当前类型System.Data.Common.DbConnection是一个抽象类,无法构造.你错过了类型映射吗?
[ResolutionFailedException:依赖项的解析失败,type ="myApp.Web.Controllers.AccountController",name ="(none)".在解决时发生异常:
在例外时,容器是:
解析myApp.Web.Controllers.AccountController,(无)解析构造函数myApp.Web.Controllers.AccountController(myApp.Web.Models.ApplicationUserManager userManager)的参数"userManager"解析myApp.Web.Models.ApplicationUserManager,(无)解析参数构造函数myApp.Web.Models.ApplicationUserManager的"store"(Microsoft.AspNet.Identity.IUserStore 1[[myApp.Web.DAL.Profiles.ApplicationUser, myApp.Web, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] store)
Resolving Microsoft.AspNet.Identity.EntityFramework.UserStore1 [myApp.Web.DAL.Profiles.ApplicationUser],(无)(从Microsoft.AspNet.Identity.IUserStore 1[myApp.Web.DAL.Profiles.ApplicationUser], (none))
Resolving parameter "context" of constructor Microsoft.AspNet.Identity.EntityFramework.UserStore1 [[myApp ]映射).Web.DAL.Profiles.ApplicationUser,myApp.Web,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null]](System.Data.Entity.DbContext context)Resolving System.Data.Entity.DbContext,(none)解析构造函数System.Data.Entity.DbContext的参数"existingConnection"(System.Data.Common.DbConnection existingConnection,System.Data.Entity.Infrastructure.DbCompiledModel model,System.Boolean contextOwnsConnection)Resolving System.Data.Common.DbConnection,(没有)
帐户控制器,因为我已修改它
public AccountController(ApplicationUserManager userManager)
{
_userManager = userManager;
}
private ApplicationUserManager _userManager;
Run Code Online (Sandbox Code Playgroud)
我已注册的容器
container.RegisterType<ApplicationUserManager>(new HierarchicalLifetimeManager());
container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(new HierarchicalLifetimeManager());
Run Code Online (Sandbox Code Playgroud) asp.net-mvc dependency-injection unity-container asp.net-identity asp.net-identity-2
我们的应用程序有很多对Task.Factory.StartNew(Action动作)的调用.不幸的是,在执行此操作时,未设置文化,此外,没有错误处理.我从一个可以同时执行这两个操作的入门类开始:
public static class TaskBuilder
{
private static Action<System.Exception> _exceptionCallback;
public static Task StartNew(Action action, CultureInfo cultureInfo, Action<System.Exception> exceptionCallback)
{
_exceptionCallback = exceptionCallback;
return Task.Factory.StartNew(() =>
{
Thread.CurrentThread.CurrentUICulture = cultureInfo;
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureInfo.Name);
action.Invoke();
}).ContinueWith(t => ManageException(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
}
private static void ManageException(System.Exception e)
{
if (_exceptionCallback != null)
{
_exceptionCallback(e);
}
}
}
Run Code Online (Sandbox Code Playgroud)
但后来我意识到更好的方法是拦截器.我想拦截对StartNew的调用,以便新线程包含文化和错误处理代码.我的尝试产生了以下代码:
public class TaskInterceptionHandler : ICallHandler
{
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
Thread.CurrentThread.CurrentUICulture = // How do I get parent cultureInfo?;
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureInfo.Name); …Run Code Online (Sandbox Code Playgroud) unity-container ×10
c# ×7
.net ×2
generics ×2
api ×1
app-config ×1
asp.net ×1
asp.net-mvc ×1
interception ×1
json ×1
unity2.0 ×1