我需要将我的统一配置拆分为 n 个不同的文件,以便我可以将其中的一些文件选择到同一个统一容器中?
我使用的是基本的Unity MVC Nuget Bootstrapper.我想将当前登录的用户注入我定义的服务中
_container.RegisterType<IDoSomethingService, DoSomethingService>();
Run Code Online (Sandbox Code Playgroud)
这样DoSomethingService获取ICurrentUser对象或某种形式的解析器.
我试图避免不得不拨打电话
DoSomethingService.DoSomething(currentUserUsingService,...);
Run Code Online (Sandbox Code Playgroud)
或者在所有MVC控制器的构造函数中也避免设置:
DoSomethingService.CurrentUSer = User.Identity.Name;
Run Code Online (Sandbox Code Playgroud) asp.net-mvc asp.net-membership unity-container asp.net-mvc-3
我有以下代码
var container = new UnityContainer(); //LINE 1
container.RegisterType<ILogUtility,LogUtil>(); //LINE 2
var logger = container.Resolve<Logger>(); //LINE 3
logger.Log(LogType.Warn, "logging from container"); //LINE 4
Run Code Online (Sandbox Code Playgroud)
如何在web.config中实现第2行,这样我只需要在我的代码中编写第1,3和4行代码?我已经在每个地方搜索代码示例,但它们并不清楚.
谢谢
c# asp.net dependency-injection inversion-of-control unity-container
编写以下代码是否正常:
protected void Application_BeginRequest()
{
var container = new UnityContainer()
.RegisterType<IUnitOfWork, MyEntities>()
HttpContext.Current.Items["container"] = container;
ServiceLocator.SetLocatorProvider(
() => new UnityServiceLocator(container));
}
protected void Application_EndRequest()
{
var container = HttpContext.Current.Items["container"]
as UnityContainer;
if (container != null)
{
container.Dispose();
}
}
Run Code Online (Sandbox Code Playgroud)
或者为每个请求注册依赖项是一种不好的做法?
谢谢.
.net asp.net dependency-injection ioc-container unity-container
我正在使用 Patterns and Practices 的 Unity 将依赖项注入到我的对象中,并且遇到了一个奇怪的(无论如何对我来说)问题。这是我的类定义:
public class ImageManager : IImageManager
{
IImageFileManager fileManager;
public ImageManager(IImageFileManager fileMgr)
{
this.fileManager = fileMgr;
}
}
public class ImageFileManager : IImageFileManager
{
public ImageFileManager(string folder)
{
FileFolder = folder;
}
}
Run Code Online (Sandbox Code Playgroud)
这是注册我的课程的代码
container.RegisterInstance<MainWindowViewModel>(new MainWindowViewModel())
.RegisterType<IPieceImageManager, PieceImageManager>(
new InjectionConstructor(typeof(string)))
.RegisterType<IImageFileManager, ImageFileManager>()
.RegisterType<IImageManager, ImageManager>(
new InjectionConstructor(typeof(IImageFileManager)));
Run Code Online (Sandbox Code Playgroud)
我最初在这样的 XAML 文件背后的代码中解决了这个问题(我知道,它违背了目的。请耐心等待。)
IImageManager imageManager = MvvmViewModelLocator.Container.Resolve<IImageManager>(
new ParameterOverride("folder", "/images"));
Run Code Online (Sandbox Code Playgroud)
它奏效了。但是我为我的主视图创建了一个视图模型,当我将同一行复制到其中时,出现异常。以下是两个最内在的例外:
InnerException: Microsoft.Practices.Unity.ResolutionFailedException
HResult=-2146233088
Message=Resolution of the dependency failed, type = "SwapPuzzleApp.Model.IImageManager", name = "(none)".
Exception occurred while: …Run Code Online (Sandbox Code Playgroud)
我有以下代码用 Unity 初始化实例:
IUnityContainer container = new UnityContainer();
container.RegisterType<DbContext, VotingSystemContext>(new PerRequestLifetimeManager(), new InjectionConstructor());
container.RegisterType(typeof(IGenericRepository<>), typeof(GenericRepository<>));
container.RegisterType<IUnitOfWork, UnitOfWork>(new PerRequestLifetimeManager());
container.RegisterTypes(
AllClasses.FromAssemblies(
Assembly.GetAssembly(typeof(IUserService)),
Assembly.GetAssembly(typeof(UserService))),
WithMappings.FromMatchingInterface,
WithName.Default, WithLifetime.PerResolve);
DependencyResolver.SetResolver(new Unity.Mvc4.UnityDependencyResolver(container));
GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
Run Code Online (Sandbox Code Playgroud)
我使用PerRequestLifetimeManager所以我遵循了MSDN上的建议并在上面的代码末尾添加了新行:
DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
Run Code Online (Sandbox Code Playgroud)
但是在我放置之后。当页面(仅静态 html)加载时,我将 ajax 请求发送到我的 WebApi 控制器,该控制器调用GenericReposirory Get()抛出错误的方法:The operation cannot be completed because the DbContext has been disposed.
没有这行代码一切正常,但没有设置它可能不会处理上下文。
我的UnitOfWork班级:
public class UnitOfWork : IUnitOfWork, IDisposable
{
private readonly VotingSystemContext _context;
private bool _disposed;
//GenericRepository properties
private void Dispose(bool …Run Code Online (Sandbox Code Playgroud) 这些天我经常面临这种情况,我正在寻找一个优雅的解决方案。我有 :
public abstract class TypeA
{
public abstract void AbtractMethod(IDependency dependency);
}
public class TypeB : TypeA
{
public override void AbtractMethod(ISpecializedDependencyForB dependency) { }
}
public class TypeC : TypeA
{
public override void AbtractMethod(ISpecializedDependencyForC dependency) { }
}
public interface IDependency { }
public interface ISpecializedDependencyForB : IDependency { }
public interface ISpecializedDependencyForC : IDependency { }
Run Code Online (Sandbox Code Playgroud)
我的目标是在客户端的角度使事情变得透明,并像这样使用这段代码:
TypeA myDomainObject = database.TypeARepository.GetById(id); // The important point here is that I don't know if the object is of …Run Code Online (Sandbox Code Playgroud) 我正在尝试一个示例应用程序来测试依赖注入.在使用DI之前,我的课程中有以下方法:
public IQueryable<BookDTO> GetBooks()
{
var books = from b in db.Books
select new BookDTO()
{
Id = b.Id,
Title = b.Title,
AuthorName = b.Author.Name
};
return books;
}
Run Code Online (Sandbox Code Playgroud)
BookDTO是另一个项目中定义的数据传输对象.现在我想把我的项目松散地结合在一起.所以我创建了IDTOBase接口并使BookDTO实现了这一点.我有一个统一容器,我已经将BookDTO类的相关注册到IDTOBase.
但是,如何在原始方法中重写LINQ查询?什么将取代"新BookDTO()"?
谢谢
c# linq dependency-injection data-transfer-objects unity-container
我是一个Unity noob,我有一个问题.我想在每个IPerson实例中注入一个IAgeCalculator,以便IAgeCalculator实例可供我以后创建的任何IPerson使用.
这是我到目前为止所尝试的.它有效,但感觉不对.
static void Main(string[] args)
{
IUnityContainer container = new UnityContainer();
container.RegisterType<IAgeCalculator, AgeInYearsCalculator>("Years");
container.RegisterType<IAgeCalculator, AgeInDaysCalculator>("Days");
// Using the initializer like this does not feel right,
// but I cant think of another way...
var ageCalculator = container.Resolve<IAgeCalculator>("Days");
var personInitializer = new InjectionMethod("Initializer", ageCalculator);
container.RegisterType<IPerson, Person>(personInitializer);
var person1 = Factory<IPerson>.Create(container);
person1.Name = "Jacob";
person1.Gender = "Male";
person1.Birthday = new DateTime(1995, 4, 1);
var person2 = Factory<IPerson>.Create(container);
person2.Name = "Emily";
person2.Gender = "Female";
person2.Birthday = new DateTime(1998, 10, 31);
} …Run Code Online (Sandbox Code Playgroud) 我有以下Unity相关问题.下面的代码存根设置基本方案,问题位于底部.
注意,该[Dependency]属性不适用于下面的示例并导致StackoverflowException,但构造函数注入确实有效.
注意(2)下面的一些评论开始分配"标签",如代码气味,糟糕的设计等......因此,为了避免混淆,这里是没有任何设计的业务设置.
这个问题似乎引起了一些最着名的C#大师的严重争议.事实上,这个问题远远超出了C#,它更多地涉及纯粹的计算机科学.问题是基于服务定位器模式和纯依赖注入模式之间众所周知的"战斗":https://martinfowler.com/articles/injection.html vs http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern /以及后续更新以解决依赖注入过于复杂时的情况:http://blog.ploeh.dk/2010/02/02/RefactoringtoAggregateServices/
这是一种情况,它不能很好地适应前两种情况,但似乎完全符合第一种情况.
我有一个大的(50+)集合,我称之为微服务.如果您有更好的名字,请在阅读时"申请".它们中的每一个都在一个对象上运行,我们称之为引用.但是,元组(上下文+引用)似乎更合适.Quote是一个业务对象,它被处理并序列化为数据库,上下文是一些支持信息,这在处理报价时是必要的,但不保存到数据库中.其中一些支持信息实际上可能来自数据库或某些第三方服务.这是无关紧要的.装配线作为一个现实世界的例子浮现在脑海中:装配工人(微服务)接收一些输入(指令(上下文)+部件(引用)),处理它(根据指令和/或修改指令对部件做某事)并且如果成功则将其进一步传递或在发生问题时丢弃它(引发异常).微服务最终被捆绑到少数(约5个)高级服务中.这种方法线性化了一些非常复杂的业务对象的处理,并允许将每个微服务与所有其他服务分开测试:只需给它一个输入状态并测试它产生预期的输出.
这是有趣的地方.由于涉及的步骤数量多,高级服务开始依赖于许多微服务:10+以上.这种依赖性很自然,它只反映了底层业务对象的复杂性.最重要的是,微服务几乎可以在不断的基础上添加/删除:基本上,它们是一些业务规则,几乎像水一样流畅.
这与Mark上面的建议严重冲突:如果我在一些高级服务中有10个以上有效的独立规则应用于某个高级服务的引用,那么,根据第三个博客,我应该将它们聚合成一些逻辑组,比如说不超过3-4而不是注入所有10+通过构造函数.但是没有合乎逻辑的团体!虽然有些规则是松散依赖的,但大多数规则都没有,因此人为地将它们捆绑在一起会带来更多弊大于利.
抛出规则经常变化,它变成了维护的噩梦:每次规则改变时,所有真实/模拟的呼叫都必须更新.
我甚至没有提到规则是美国依赖的,因此,理论上,大约有50个规则集合,每个州和每个工作流程都有一个集合.虽然一些规则在所有州之间共享(例如"保存对数据库的引用"),但是有很多州的具体规则.
这是一个非常简单的例子.
引用 - 业务对象,它被保存到数据库中.
public class Quote
{
public string SomeQuoteData { get; set; }
// ...
}
Run Code Online (Sandbox Code Playgroud)
微服务.他们每个人都会执行一些小的更新来引用.也可以从一些较低级别的微服务构建更高级别的服务.
public interface IService_1
{
Quote DoSomething_1(Quote quote);
}
// ...
public interface IService_N
{
Quote DoSomething_N(Quote quote);
}
Run Code Online (Sandbox Code Playgroud)
所有微服务都继承自此接口.
public interface IQuoteProcessor
{
List<Func<Quote, Quote>> QuotePipeline { get; }
Quote ProcessQuote(Quote quote = null);
}
// Low …Run Code Online (Sandbox Code Playgroud)