标签: unity-container

再次关于log4net和Unity IOC配置

我已经碰到了围绕各个网站提出的一些问题,答案似乎是由l4n officianados转向了log4net'是'的轻量级包装器的价值(你不明白吗?)和类似的观点令人难以置信的事实.

然而,似乎用户要求的(这是我的问题)是如何使log4net objet模型适应fluent配置界面中的registertype/registerinstance序列.

这里的目标不是重新包装l4n,而只是为了获得一个不需要劫持流畅流量的体面参考,就像它一样.

糟糕的ejemplow,我想从LogManger.GetLogger方法获得对已配置的ILog实例的引用,并将其尽早放入流体流中,以将其注入我的下游对象的属性中.

因此,为了回应一个不耐烦的建议,我尝试以规范的方式创建了一个正常的ILog实例:

log4net.Config.XmlConfigurator.Configure();
static readonly log4Net.Ilog Log = LogManager.GetLogger(thatlongassemblyreflectionstuff);
Run Code Online (Sandbox Code Playgroud)

因此,现在将这个引用添加到Unity容器并继续我的美好生活似乎是微不足道的(在真正意义上毫不费力).

但是,RegisterInstance方法的签名需要"类型"而不是接口.

对于那些没有搜索过log4net对象模型的人来说,afficiananderos是正确的:l4n是一个"包装器",你无法得到Log thingie的实际"类型".

所以现在我必须测试.你知道这意味着什么,它可能需要一分钟,但更可能需要一个小时或四个(类似于'小时'和'四'的拼写在现实生活中从来不是巧合).

但是,以下内容除了关于规范设置的省略部分外,确实有效:

container
  .RegisterInstance("Logger", Log, new ContainerControlledLifetimeManager())
.RegisterType<IControllerContext, ControllerContext>
(
   "CtlrCtx", 
   new ContainerControlledLifetimeManager(), 
   new InjectionConstructor(new ResolvedParameter<IMessageBuilder>("MsgBldr")),
   new InjectionProperty("Log",new ResolvedParameter<ILog>("Logger"))
);
Run Code Online (Sandbox Code Playgroud)

因此,原始Log对象的哈希码和注入到我的marvy小对象对象的属性中的Log对象是相同的.

然而...

注入过程要求我通过其接口公开Context对象的Log属性,这意味着它不再是静态对象.并且log4net ILog对象是否是静态的似乎是决定它是否可序列化并且可以在程序集之间进行编组而没有戏剧性的"运行时将变得不稳定"警告(这对于Matrix粉丝来说真正有意义).

气馁,虽然没有阻止,但我使用Resharper的漂亮'带有支持字段的属性'并将支持字段设置为静态,而Interface属性保持非静态.它建成了,测试运行绿色.

所以我甚至进行了重建并且有效.所以也许当这个泡沫达到集成测试时,我会偷偷溜过log4net,这不是可序列化的崩溃.

所以也许这会有所帮助

谢谢

Stato

configuration log4net unity-container

5
推荐指数
1
解决办法
5114
查看次数

使用ServiceLocator进行单元测试

我正在对使用统一依赖注入框架的类进行单元测试.

返回null:ServiceLocator.Current.GetInstance();

我怎样才能让它返回一个模拟对象或只是对象本身?

unit-testing unity-container

5
推荐指数
2
解决办法
6867
查看次数

Log4net和Unity注册

我正在尝试配置Unity以将ILog注入到我的类中,其中LogManager.CreateLogger()中的类型/名称被设置为注入ILog的类.

这是一个类似的问题,但对于结构图

log4net unity-container

5
推荐指数
1
解决办法
2065
查看次数

如何做好莱坞原则+ DI + WPF + Unity

我现在开始开发一个新的WPF应用程序,我使用Unity作为DI容器.截至目前,我在App.xaml.cs中正在做这样的DI

protected override void OnStartup(StartupEventArgs e)
    {
        var container = new UnityContainer();
        UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
        container = (UnityContainer)section.Configure(container);
        WPFUnityContainer.Instance = container;

        var mainwindow = new MainWindow();
        var mainmodel = container.Resolve<ViewModel.MainWindowViewModel>();
        mainwindow.DataContext = mainmodel;
        mainwindow.Show();

        base.OnStartup(e);
    }
Run Code Online (Sandbox Code Playgroud)

MainWindowViewModel的ctr如下所示:

public MainWindowViewModel(IUserRepository userRepository, IGroupRepository groupRepository)
    {
        this._ManagementWorkSpaces = new ObservableCollection<WorkspaceViewModel>();
        this._ManagementWorkSpaces.Add(new ManageApplicationsViewModel());
        this._ManagementWorkSpaces.Add(new ManageUserViewModel(userRepository, groupRepository));

    }
Run Code Online (Sandbox Code Playgroud)

现在让我们看一下ManageUserViewModel:

public ManageUserViewModel(IUserRepository userRepository, IGroupRepository groupRepository)

    {...
      this._ManageGroupsCommand = new DelegateCommand(() =>
        {
            LookupGroupDialogViewModel vm=new LookupGroupDialogViewModel(groupRepository);
            View.LookupGroupDialogWindow vw=new View.LookupGroupDialogWindow();
            ModalDialogService.Service.ShowDialog(vw, vm, returnedVM =>
                {
                    if (returnedVM.SelectedGroup!=null) …
Run Code Online (Sandbox Code Playgroud)

wpf dependency-injection unity-container

5
推荐指数
1
解决办法
399
查看次数

Unity中调用站点截获方法的完整堆栈跟踪

我们正在研究使用Unity来处理带有拦截的日志服务方法.但是,一个问题是呼叫站点没有完整的堆栈跟踪; 它只在拦截器调用中可用.

这是一个示例设置:

public interface IExceptionService
{
    void ThrowEx();
}

public class ExceptionService : IExceptionService
{
    public void ThrowEx()
    {
        throw new NotImplementedException();
    }
}

public class DummyInterceptor : IInterceptionBehavior
{
    public IEnumerable<Type> GetRequiredInterfaces()
    {
        return Type.EmptyTypes;
    }

    public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
    {
        IMethodReturn ret = getNext()(input, getNext);
        if (ret.Exception != null)
            Console.WriteLine("Interceptor: " + ret.Exception.StackTrace + "\r\n");
        return ret;
    }

    public bool WillExecute
    {
        get { return true; }
    }
}

class Program
{
    static void Main(string[] …
Run Code Online (Sandbox Code Playgroud)

.net unity-container unity-interception

5
推荐指数
1
解决办法
2135
查看次数

信号器 + 统一 DI

我已经通过常规方法成功地在我的 MVC4 项目中使用了 Signalr,方法是设置一个普通的集线器,包括 JS 文件/signalr/hubs并且它可以工作。

现在我正在尝试统一设置 DI:

Global.asax

UnityContainer = Bootstrapper.Initialise();
var unityDependencyResolver = new UnityDependencyResolver(UnityContainer);

// Used for MVC
DependencyResolver.SetResolver(unityDependencyResolver);

// Used for SignalR
GlobalHost.DependencyResolver = new SignalRUnityDependencyResolver(UnityContainer);

RouteTable.Routes.MapHubs();
Run Code Online (Sandbox Code Playgroud)

Bootstrapper.cs

public static IUnityContainer Initialise()
{
    var unityContainer = new UnityContainer();

    unityContainer.RegisterType<IUsers, Users>();

    unityContainer.RegisterType<ChatHub>(new InjectionFactory(CreateMyHub));

    return unityContainer;
}

private static object CreateMyHub(IUnityContainer p)
{
    return new ChatHub(p.Resolve<IUsers>());
}
Run Code Online (Sandbox Code Playgroud)

和集线器: public class UserHub : Hub { private readonly IUsers _users;

public ChatHub(IUsers users)
{
    _users = users; …
Run Code Online (Sandbox Code Playgroud)

unity-container asp.net-mvc-4 signalr

5
推荐指数
1
解决办法
905
查看次数

mvc 将 httpcontext 注入服务层

在将 httpContextBase 注入到使用 unity 注入控制器的服务级别对象中时,我遇到了一个大问题。

样品控制器

public HomeController : Controller{
    private IWorkContext _context;

    public HomeController(IWorkContext context){
        _context = context;
    }

}


public WorkContext : IWorkContext{

    private HttpContextBase _httpContext;

        public (HttpContextBase httpContext){
            _httpContext = httpContext;
        }

        public void DealWithCookies(){
            //do some thing with http context and deal with cookies
        }
    }
Run Code Online (Sandbox Code Playgroud)

内部统一引导程序

container.RegisterType<HttpContextBase>().RegisterInstance(new HttpContextWrapper(HttpContext.Current) as HttpContextBase, new ContainerControlledLifetimeManager());

//With this line httpcontextbase is returned but as a singleton instead of new for each request.


   container.RegisterType<HttpContextBase>().RegisterInstance(new HttpContextWrapper(HttpContext.Current) as HttpContextBase, new PerRequestLifetimeManager());

//This …
Run Code Online (Sandbox Code Playgroud)

asp.net-mvc unity-container code-injection

5
推荐指数
1
解决办法
2577
查看次数

统一拦截概念清晰度

我正在关注Unity Interception链接,在我的项目中实现Unity.

通过链接我创建了一个类,如下所示:

[AttributeUsage(AttributeTargets.Method)]
public class MyInterceptionAttribute : Attribute
{

}

public class MyLoggingCallHandler : ICallHandler
{
    IMethodReturn ICallHandler.Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
    {
        IMethodReturn result = getNext()(input, getNext);
        return result;
    }
    int ICallHandler.Order { get; set; }
}

public class AssemblyQualifiedTypeNameConverter : ConfigurationConverterBase
{
    public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
    {
        if (value != null)
        {
            Type typeValue = value as Type;
            if (typeValue == null)
            {
                throw new ArgumentException("Cannot convert type", typeof(Type).Name); …
Run Code Online (Sandbox Code Playgroud)

c# unity-container unity-interception

5
推荐指数
1
解决办法
469
查看次数

如何构建单元工作/服务层/存储库,以便它们与DI(Unity)和Moq一起用于单元测试

我有一个MVC应用程序(EF6,SQL Server CE 4),我最近重构了添加一个UnitOfWork类和一个服务层(这样我可以使用DbContext每个请求一个,并成功执行事务).

以前,我使用Unity将存储库注入控制器.我的单元测试(对于控制器)设置简单 - 我只是模拟每个存储库,并将它们传递给控制器​​构造函数.

在重构之后,我现在使用Unity注入服务层(到控制器)和UnitOfWork(到服务层).服务层现在通过传递UnitOfWork.DbContext给存储库的构造函数来实例化每个存储库.

在我的单元测试中,我试图模拟UnitOfWork和ServiceLayer(并将模拟UnitOfWork对象传递给ServiceLayer的构造函数).但是,测试失败,说"在ControllerTest中TestFixtureSetup失败".

我认为这是由于我试图将UnitOfWork模拟传递给ServiceLayer模拟器,因此将非常感谢有关如何正确执行此操作的任何指导.

相关代码片段如下.

的UnitOfWork

public interface IUnitOfWork:IDisposable
{
    void Save();
    IDSMContext Context { get; }
}

public class UnitOfWork : IUnitOfWork, IDisposable
{
    private IDSMContext _context;

    public UnitOfWork()
    {
       _context = new IDSMContext();
    }

    public IDSMContext Context
    {
        get {return _context;}
    }

    public void Save()
    {
        _context.SaveChanges();
    }

    private bool disposed = false;

    protected virtual void Dispose(bool disposing) …
Run Code Online (Sandbox Code Playgroud)

entity-framework moq unity-container unit-of-work repository-pattern

5
推荐指数
1
解决办法
1314
查看次数

当前类型IUserStore <ApplicationUser>和DbConnection分别是接口和抽象类,不能构造

如果我冲浪,http://localhost:58472/Account/Register我就有这个例外

System.InvalidOperationException:当前类型IUserStore<ApplicationUser>是一个接口,无法构造.你错过了类型映射吗?

这是我的代码:

public class ApplicationUserManager : UserManager<ApplicationUser>
{
    public ApplicationUserManager(IUserStore<ApplicationUser> store)
        : base(store)
    { }

    public static ApplicationUserManager Create(
        IdentityFactoryOptions<ApplicationUserManager> options, 
        IOwinContext context) 
    {
        var manager = new ApplicationUserManager(
            new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>())
        );

        // other code
        return manager;   
    }
}
Run Code Online (Sandbox Code Playgroud)

这里是控制器的代码:

[Authorize]
public class AccountController : Controller
{
    private ApplicationSignInManager _signInManager;
    private ApplicationUserManager _userManager;

    public AccountController()
    {
    }

    public AccountController(
        ApplicationUserManager userManager,
        ApplicationSignInManager signInManager)
    {
        UserManager = userManager;
        SignInManager = signInManager;
    }

    public ApplicationSignInManager SignInManager …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-mvc user-management unity-container invalidoperationexception

5
推荐指数
1
解决办法
6062
查看次数