1

我正在尝试使用 XSockets 来实现服务器,并且我想使用 DI 抽象 DB 层。

这就是我所拥有的:

public class FooController : XSocketController
{
    // constructor
    public FooController()
    {
        // initialize some data here
    }
    //... rest of class
}

这就是我想要的(为了能够在用作服务器的控制器上使用一些 DI):

public class FooController : XSocketController
{
    private IBar _myBar;

    // constructor
    public FooController(IBar BarImplementation)
    {
        // ...
        _myBar = BarImplementation;
    }
    //... 
}

问题是:我自己实际上并没有创建 FooController,当一些客户端尝试连接到它时,它会被调用。
这是启动服务器的典型用法:

_serverContainer = Composable.GetExport<IXSocketServerContainer>();
_serverContainer.StartServers();

// Write info for each server found.
foreach (var server in _serverContainer.Servers)
{
    Console.WriteLine(server.ConfigurationSetting.Endpoint);
    Console.WriteLine(  "Allowed Connections (0 = infinite): {0}",
                        server.ConfigurationSetting.NumberOfAllowedConections);
}

如果我没记错的话(我很可能是这样),当客户端尝试连接时,他会获得自己的私有控制器作为服务器。

关于如何解决这个问题的任何想法?

4

2 回答 2

1

有几种方法可以做到这一点,但(目前)没有办法在控制器上注入构造函数。你可以在你自己定义的其他类上使用它......

这是一种方法。

/// <summary>
/// Interface with export attribute
/// </summary>
[Export(typeof(IBar))]
public interface IBar
{
    void SomeMethod();
}

/// <summary>
/// Implementation of IBar
/// </summary>
public class Bar : IBar
{
    public void SomeMethod()
    {

    }
}

/// <summary>
/// Controller with IBar property
/// </summary>
public class Foo : XSocketController
{
    private IBar bar;

    public Foo()
    {
        bar = Composable.GetExport<IBar>();
    }
}

编辑:回答评论中的问题。这

GetExport<T> 

期望只找到一个实现该接口的实例。如果你有多个类实现你的接口,你应该使用

GetExports<T>

我们没有构造函数注入等的原因是大多数时候人们添加了某种 IService 或 IRepository。这将打开一个数据库连接,只要控制器存在,它就会一直打开,只要客户端连接就可以了。那很糟糕:)所以当你需要数据访问时,你应该使用

GetExport<IMyService>

使用它,然后当您退出该方法时,连接将被关闭。

您当然也可以使用 Ninject 等,但您仍然应该只在尽可能短的时间内创建具有数据访问权限的对象。

于 2014-05-27T05:39:13.543 回答
1

只是一些额外的信息。在下一个版本(明天 4.0 alpha)中,您将能够喜欢这个

/// <summary>
/// Interface with export attribute
/// </summary>
[Export(typeof(IBar))]
public interface IBar
{
    void SomeMethod();
}

/// <summary>
/// Implementation of IBar
/// </summary>
public class Bar : IBar
{
    public void SomeMethod()
    {

    }
}

然后使用像这样的 ImportingConstrcutor ...

/// <summary>
/// Controller with IBar property
/// </summary>
public class Foo : XSocketController
{
    public IBar Bar { get; set; }

    public Foo(){}

    [ImportingConstructor]
    public Foo(IBar bar)
    {
        this.Bar = bar;
    }
}

或者像这样使用 ImportOne...

/// <summary>
/// Controller with IBar property
/// </summary>
public class Foo : XSocketController
{
    [ImportOne(typeof(IBar))]
    public IBar Bar { get; set; }
}
于 2014-05-27T08:14:23.217 回答