S7NetPlus / s7netplus

S7.NET+ -- A .NET library to connect to Siemens Step7 devices
MIT License
1.3k stars 581 forks source link

How do I access to Plc (instance) from other classes. #255

Open Mallowan opened 4 years ago

Mallowan commented 4 years ago

hello, for example, there's known way (according to docs) to do that in MainWindow.

public Plc plc;
plc = new Plc(CpuType.S71200, "100.1.1.10", 0, 0);

Could anyone share an example, which shows access to Plc from other classes?

thank you in advance!

MiroslavMikus commented 4 years ago

Hey, the base idea should be to use Dependency Injection.

We are using Autofac. Here is the simplified version:

var builder = new ContainerBuilder();

builder.Register<Plc>(()=> new Plc(CpuType.S71200, "100.1.1.10", 0, 0));

var scope = builder.Build();

var yourService =  scope.Resolve<Service>();

Where the Service requests the Plc in the constructor:

public class Service
{
    public Service(Plc myPlc)
    {

    }
}

Let me know if you have still some problems :)

Mallowan commented 4 years ago

hi there, I will try to replicate that, then there will be questions definetely. Thanks!

OOOOO1 commented 4 years ago

嘿,基本思路应该是使用依赖注入

我们正在使用Autofac。这是简化版:

var builder = new ContainerBuilder();

builder.Register<Plc>(()=> new Plc(CpuType.S71200, "100.1.1.10", 0, 0));

var scope = builder.Build();

var yourService =  scope.Resolve<Service>();

Service请求Plc在构造函数:

public class Service
{
    public Service(Plc myPlc)
    {

    }
}

让我知道您是否还有一些问题:)

您好,按照你说的,我尝试复制你的代码,结果出现 Error CS1593 Delegate 'Func<IComponentContext, Plc>' does not take 0 arguments

MiroslavMikus commented 4 years ago

Hey, I do speak just ENG / GER so maybe this answer will not be directly on point. Anyway, it looks like you are using a different version of Autofac. Pls try this:

builder.Register<Plc>(CONTEXT => new Plc(CpuType.S71200, "100.1.1.10", 0, 0));

A second fix could be to bump your Autofac dependency to at least 4.9.1

Best regards Miro